Hamburger responsive menu not closing
Hi! It is my first time trying to edit a hamburger menu for resposive view, it works well except it wont really close after clicking the X, what can I do?
Code is here: https://codepen.io/luakenai/pen/VYZzyRa
Thank you in advance!
7 Replies
its working for me
nvm
At first glance, your btnMenu variable is not defined.
this declaration
const div = document.querySelector(".btn-menu", "#mobile", ".menu");
is not valid. querySelector
takes a single string.
const div = document.querySelector(".btn-menu, #mobile, .menu");
This selector will return the first element that matches any of the specified selectors (.btn-menu, #mobile, or .menu) but not all of them so your 'div' variable is actually referencing .btn-mobile
. You can see this if you log console.log(div)
SInce you want separate references to each of these elements you mostly likely want something like
Given this mixup, im not certain which element you're wanting to toggle the 'active' class on since there is nothing in the css that uses the .active class. In one function youre setting it on the div
and in another function youre setting it on the nav
(which there is no nav
defined). Also not sure which element should be getting the data-target attribute and why;
And your event listeners, idk what device youre testing on but consider using click events instead of or in addition to touchstart for better cross-device compatibility. You've got a function handleButtonClick
on a touchStart event listener.
Additionally instead of targetElement.getAttribute("data-target", "");
i think you wanted targetElement.setAttribute("data-target", "");
Oh! That is helpful, will apply it to my code thank you ☺️
also, data attributes can be accessed directly without the get/set Attribute method
targetElement.dataset.target = ""
example of usage:If you have an attr like [data-target-text-el], would you just reference it like
dataset.targetTextEl
?
I always forget when there’s multiple hyphens, if it just needs to be camelCase ?yes, hypens after data- are replaced by camelcasing
so everything is lowercased and every dash makes it combined using camelcasing.