Day 7: CSS Toggles with element.classList
Reminders for Tony
- Put on mic
- Open Zoom chat
- Record! Anyone else?
Housekeeping
- PROJ 207 Group Assignment (details listed on this home page)
- Presentation: Friday, Aug 7
- Code submission deadline: Aug 10
- Group size: 3-4
- How do you want to choose groups?
Prep
- Important: JavaScript Tutorial for Beginners by Mosh Hamedani
- This is an excellent overview of the starter JS concepts you’ll need for the rest of this course.
- There is a handy Table of Contents in the video description.
- Tissue Contrast Illusion: we will be regularly borrowing code from this article for our frontend Javascript lessons.
Goal for the day
By the end of the day, you should have a button that toggles a CSS class.
Topics Covered
- Firefox Console
- JS: ‘Element.classList’
- JS: `Element.addEventListener()’
- You will see the keyword
thisused a lot in examples online. For now, avoid the use ofthisuntil we cover it later in the course. If you just can’t wait: the value ofthiswithin an event handler
- You will see the keyword
Topic 1: Introducing the Document Object Model (DOM)
When we target an HTML element (ex, a <p>) with a new CSS declaration (ex, color: darkgoldenrod), we are changing settings of the Document Object Model.
Live-code objectives
In this live-code session, we will explore the Firefox Console (Chrome works too).
- Create an empty HTML file in your editor and view it in a browser.
- Open the Inspector, navigate to the Console and enter the following as separate statements. What does the console return?
"hello world!"(include the quotes)41 + 23 / 04 < 5innerHeightinnerWidthdocument- try any other valid js statement
Activity: Creating a DOM element variable with the id attribute
You will be working in pairs. We are going to inspect the body element (of the page we just created) and discover where class names are stored in the DOM.
- Try entering the following in the console:
body-> should return an error; “body” doesn’t mean anything, yet.
-
Now, add an
idto<body>:<body id="body"> - Try repeating Step 1. What happens?
body-> should now return a DOM element. This means that, simply by giving the element anid, we have created a variable named “body” that references the page’sbodyelement. We’ll look at better ways to do this later in the course.- Try changing the
idto something other than “body”. Does this affect the variable name we need to enter into the console? - Notice the triangle next to the returned body element. Click on it and find
classListin the resulting list. What’s its length?
-
Add a class (your choice) to the body tag:
<body id="body" class="fancy-bg"> - Repeat Step 3 and inspect the body element. How has
classListchanged? What value doesclassNamehold? - Try adding/removing different classes to the
bodytag and re-inspect the element to see howclassListandclassNamechanges. What do you thinkclassNamerepresents?
Topic 2: Adding and Removing classes with element.classList
Using the console, we’re going to become more familiar with the classList API. classList is a Javascript Object, so we need to use dot notation to access the goodies:
classList.add()-> adds a classclassList.remove()-> removes a classclassList.toggle()-> described belowclassList.contains()-> returnstrueorfalseclassList.replace()-> rarely used but nice to have
Live-code objectives
Let’s add a class declaration to help us understand element.classList() visually. Add this CSS declaration to your page:
.fancy-bg {
background-color: rebeccapurple;
}
Using the console, use the classList API to:
- add the class “split-bg” to the
bodyelement usingclassList.add()(remember the console will accept any valid Javascript statement); - remove the same class from the
bodyelement usingclassList.remove(); - toggle the “split-bg” class using
classList.toggle().
classList.toggle() is a nice shortcut method that saves us from coding a conditional like the following:
// Notice the use of classList.contains(). This method returns true or false; perfect for if/then statements.
if (body.classList.contains("split-bg")) {
// .split-bg exists so let's remove it...
body.classList.remove("split-bg");
} else {
// .split-bg doesn't exist so let's add it...
body.classList.add("split-bg");
}
Activity: Class action!
Now that you can add/remove/toggle classes that are assigned to an element, add another HTML element (your choice). What other declarations can you define in CSS that you can add/remove as class names using classList.toggle() from within the console?
Mid-day Huddle
- who needs help?
- any pivots?
- any show-and-tell?
[lunch]
Topic 3: Toggling CSS with a button event listener
We now know how to add/remove/toggle classes but the console probably isn’t the best way to do this. Let’s add a button to our page and use it to toggle a class with an event listener.
Live-code objectives
Event Listeners can be added to any element but the button is well suited for click events.
Copy this sample code (adapted from this MDN Example) into a <script></script> element just before your </body> tag):
// Function to toggle a class name
function toggleBackground() {
body.classList.toggle('fancy-bg');
}
// Add event listener to `button`
btn.addEventListener("click", toggleBackground);
Activity: Hamburger menus
You will work in teams. Now that you know how to toggle CSS at the click of a button, discuss how this technique can be used to toggle a mobile hamburger menu.
Visit your favourite websites on your mobile device. How do they handle navigation on the smaller screen?
- Do they hide the options?
- If so, how do you show the navigation?
- If it’s a hamburger menu, are there any transitions or animations?
Summary
- any trophies?
- prep for tomorrow?
- applause