r/javaScriptStudyGroup • u/Usual_Mathematician2 • Nov 09 '20
im having problem
hi in this link there is a hamburger menu.
https://css-tricks.com/line-animated-hamburger-menu/
but when i use the codes that are in that link i posted the hamburger menu doent go back to the hamburger icon when i click on a href in the navbar
can some one help me pls
1
Upvotes
1
u/theogjpeezy Nov 09 '20
I believe you will need to introduce some type of javascript function here to listen to the navbar links. The easiest way I can imagine doing this is by adding listeners to your
nav-linkelements and removing theopenedclass when a navbar link is clicked.The logic to get this working is relatively straightforward
I broke this up a bit to be declarative so its easier to follow.
We need to get all of the elements from the navbar. We can get these elements by querying the DOM for everything with the
nav-linkclassWe need to turn this into an array so we can loop over it properly
We need to loop over our array of elements and register a listener that will fire whenever one of them is clicked. This will fire the
collapseHamburgerMenufunctionWhen the
collapseHamburgerMenufunction is fired. It will go out and query the DOM for the button, then remove theopenedclass from it. If that class isn't on it (its still showing the hamburger, not the X) it effectively does nothing.There's a jsfiddle here, https://jsfiddle.net/2a7wcgzv,showing it working. I changed the
lineclass to always have a stroke color ofblackthough so I could see everything.There are ways of doing this with less code, however, I think this makes it easy to break down and learn.
References:
Document.getElementById
Document.getElementsByClassName
EventTarget.addEventListener
Array.from
Array.forEach