Hamburger Menu Event
Let's implement the ability to open and close a menu using JavaScript code and a hamburger menu click event.
Variable Declaration:
const hamburger = document.querySelector('.hamburger');
const navMenu = document.querySelector('.nav-menu');
hamburger
: Selects the element with the.hamburger
class and assigns it to thehamburger
variable. This refers to the hamburger menu icon.navMenu
: Selects the element with the.nav-menu
class and assigns it to thenavMenu
variable. This refers to the entire navigation menu.
Add Event Listener:
hamburger.addEventListener('click', mobileMenu);
- Adds a 'click' event listener to the
hamburger
icon. When clicked, themobileMenu
function is called.
mobileMenu Function:
function mobileMenu() {
hamburger.classList.toggle('active');
navMenu.classList.toggle('active');
}
- This function toggles the 'active' class on the
hamburger
andnavMenu
elements each time it is called.
If the class already exists, it is removed; if it does not exist, it is added. This allows the CSS-defined .active
style to be applied or removed.
closeMenu Function:
function closeMenu() {
hamburger.classList.remove('active');
navMenu.classList.remove('active');
}
- This function explicitly removes the 'active' class from the
hamburger
andnavMenu
elements. Although this function is not invoked in the given code, it can be used elsewhere to close the menu when needed.
In summary, the code implements the functionality to open or close the menu each time the user clicks the hamburger icon. By adding and removing the 'active' class, the CSS-defined style changes are triggered, thus controlling the menu's visibility.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.