:hover was just a reaction to the mouse being over an element. “I want it to move only when clicked,” “I want it to go back when pressed again” — for that, JavaScript steps in. We combine addEventListener and classList, which you learned in the JS track, with CSS animation.
Make a like button
Each time you press the button, the heart toggles between bouncing into color and going back to plain.
Break down how it works
On the CSS side, all it decides is: bounce only when .is-active is on.
<button class="like">🤍</button>.like.is-active {
animation: pop 0.35s ease;
}On the JS side, each click adds or removes .is-active.
<button class="like">🤍</button>const btn = document.querySelector('.like');
btn.addEventListener('click', () => {
const active = btn.classList.toggle('is-active');
btn.textContent = active ? '❤️' : '🤍';
});classList.toggle('is-active') is a handy method that adds the class if it’s missing, and removes it if it’s there. On top of that, it returns “what state it ended up in (true/false),” so the example above uses that to switch the emoji along with it.
addEventListener and querySelector are the very same tools you learned in the JavaScript course. If you’ve forgotten, it’s fine to review and then come back.
One more: a menu that opens and closes
With the same idea, you can also make a menu open and close.
When you transition the height between concrete values like 0 and 200px, it opens and closes smoothly (height: auto can’t be transitioned, so the trick is to prepare a sufficient max-height in advance).
Summary of this lesson
- Prepare “when a class is on, move like this” in CSS, and have JS handle only adding and removing the class
classList.toggle('class-name')turns a class ON/OFF (the result comes back as true/false)- Keep the look’s rules in CSS and the timing control in JS
- You can make an open/close animation by
transition-ingmax-height
Now you have the pattern of “controlling motion by adding and removing a class.” Next time we’ll use this exact pattern and change the trigger from a click to scrolling.