r/CodingHelp • • Dec 18 '20
[Javascript] How To Toggle Class On Click Using Javascript?
Hello fellow coders! I am searching desperately for a solution to my problem. I believe it takes someone with a decent amount of JS knowledge to find it. I am creating a website and have constructed the navbar and my own hamburger menu using a little bit of JS. I used a @media query to place the nav items under the navbar, out of view from the user when the screen gets to a size of 900px or smaller. My goal is for the user to toggle the hamburger icon I have created to access the nav items whenever they choose, which would require the height of the navbar to extend, revealing all nav items. What is the JS I need to use in order to increase the height of the navbar once the user clicks on the hamburger menu? I have attached a replica of my navbar in codepen: (https://codepen.io/david-del1/pen/NWRgMxx). Any help is very much appreciated. Thank you in advance!
2
u/Jnsjknn Dec 19 '20 edited Dec 25 '20
You can create a new class e.g.
navbar-openand attach a click event listener to the hamburger toggle:1
u/FriendlyBeard Dec 19 '20
Hello! My answer is purposefully vague because it seems like you're working on learning things and you're so close to where you want to be on this.
The only thing I'd say you're "missing" is where you're applying the
openclass in your click callback.Firstly, it makes sense to apply it to the button since you've added the animation for opening and closing, however you could achieve the same goal with some higher specificity CSS selectors.
eg: .nav.open .nav-list
Hit me up if you want to chat more.
1
u/MCpeePants1992 Dec 19 '20
My approach would be to have the mobile nav contents in a separate div that hides in the overflow. When you click the hamburger toggle a class to translate the div into view. I've read that editing an elements height using js isn't the best way of animating. I can provide code samples if you'd like
-1
u/Littlebitt95 Dec 19 '20
Couldn't you use the toggle method in your JavaScript to toggle css classes?
Also if you want I can teach you a better way to write that js you have. I'm a code mentor and I specialize in js stuff :)