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
i_lost_to_loba_kreygasm
its working for me nvm
clevermissfox
clevermissfox4w ago
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
const div = document.querySelector("#mobile");
const btnMenu = document.querySelector(".btn-menu");
const menuEl = document.querySelector('#menu');
const div = document.querySelector("#mobile");
const btnMenu = document.querySelector(".btn-menu");
const menuEl = document.querySelector('#menu');
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", "");
drinking a full jug of fanta
Oh! That is helpful, will apply it to my code thank you ☺️
MarkBoots
MarkBoots3w ago
also, data attributes can be accessed directly without the get/set Attribute method targetElement.dataset.target = "" example of usage:
No description
clevermissfox
clevermissfox3w ago
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 ?
MarkBoots
MarkBoots3w ago
yes, hypens after data- are replaced by camelcasing
MarkBoots
MarkBoots3w ago
so everything is lowercased and every dash makes it combined using camelcasing.
No description

Did you find this page helpful?