JavaScript.
This code opens a navbar menu. How can I make it so that when I tap the same button it will be close?
Please explain to me in a way as if you are explaining it to a beginner. Because I am a beginner 🙂 . If possible, show me a better way of doing this.
30 Replies
https://jsfiddle.net/jphc39bf/1/
you can do something like this
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
It is not working.
provide a snippet of your code
Can we talk in a voice chat?
the code that azyrum provided shows that he used a class of "open" and when you click the button js toggles the class to the nav element
Should I put .links instead of open?
change the getElementsByClassName to querySelector(".links")
you can use whatever classname you want
I did
make sure you use querySelectorAll if more than 1 eleemnts have the links class
the .links is a div
When I tap the button it should open .links menu and close it for the second time.
you should use links.classList.toggle(".visible")
and css
.links{
display: block;
}
.visible{
display: none;
}
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Where should I put the class .visible?
Here you have a nav wrapping the button and the links div.
I store the ".links" div inside a variable.
I add an eventlistener to the button, when i click the button it gives the links div a class
on the links variable
I'll comment inside the jsfiddle
nvm
man..
@FES001 it might be useful to provide a live example like suggested in #how-to-ask-good-questions, using codepen or jsfiddle like Azyrum is doing, so that everyone has a full view of what your problem is specifically
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Ok so first
There is no .visible in the css.
If the class does not exist, nothing's going to happen
When you give a class via javascript, you only give the name of the class without the "."
So I did
Sorry, as soon as I sent that link I went to have a lunch.
Wow, it is working
Thank you so much.
no prob