On Learning toggling in JavaScript
They said that learning is fully understood when you either teach to other people.
Or when you verbalize it. Basically, it forces your brain to be active about learning, and enunciating what you'd learnt properly
And that's exactly what happened today as I'd been learning toggling
So this is what I understand -
1. You have a button that you want to add an event listener to
Let's call the function - menuIcon
const menuIcon = document.querySelector('.menu-icon');
2. After adding the event listener to the button, you create a function
menuIcon.addEventListener('click', function ( ) {
*The function goes in here*
}
3. This function role is to toggle between a class.
4. Preferably, you'd have 2 classes in place. Let's call them, "hide-links" and "show-links"
5. The "hide-links" is in the html file already and styled in the stylesheet. And for the most part, it's probably displaying "none" or "hidden"
Also, it has been saved to a variable in JavaScript like this
const hideLinks = document.querySelector('.hide-links')
6. Then, you have the second class ('show-links'), which is not in your html file already, but is styled in the stylesheet.
And you want to toggle 'on' and 'off' in the element containing the first class ("hide-links")
7. So your function will basically be this
menuIcon.addEventListener('click', function ( ) {
hideLinks.classList.toggle('show-links')
}
And that's it folks.
To show you I didn't magically learn this, but stumbled my way through, I've attached a link to 3 recordings of me trying to explain it out loud before I finally grasped it -
https://drive.google.com/drive/folders/1ZlzTC0X5-wedJgdHrVSEy9SIci7Bfps1
Comments
Post a Comment