Exercise: Anonymous functions for the accordion
Now that we understand how to use anonymous functions, let's transform our accordion code to use them:
Here is the current code inside the index.js
file:
//Select the accordion header
const accordionHeader = document.querySelector(".accordion .accordion-header");
//Add event listener and handler to it
accordionHeader.addEventListener("click", toggleAccordionContent);
//Defined a function for toggling the accordion content
function toggleAccordionContent(){
const accordion = document.querySelector(".accordion");
accordion.classList.toggle("is_open");
}
As you can see, it is currently using a named function for the event handler.
The Exercise
Replace the toggleAccordionContent
function with an anonymous function.
The solution
...
Don't read it yet :P
...
//Select the accordion header
const accordionHeader = document.querySelector(".accordion .accordion-header");
//Add event listener and handler to it
accordionHeader.addEventListener("click", function(){
const accordion = document.querySelector(".accordion");
accordion.classList.toggle("is_open");
});
In the next lesson, we will learn how to create an off-canvas menu using the same techniques real fast.