You can do it without using toggle, classList or classname. Just create two CSS shots using an attribute data-ativo
, one with display: none
so that the menu already click hidden when it is equal to false
:
ul.navigation[data-ativo='false']{
display: none;
}
And another to show the menu when the data-ativo
for true
:
ul.navigation[data-ativo='true']{
display: block;
}
When you click on the "Menu" link and the menu is closed, it will change the attribute data-ativo
for true
, and if it is open, it will change to false
, and the CSS rules will display or display the menu:
document.addEventListener("DOMContentLoaded", function(){
document.querySelector(".menuicon").addEventListener("click", function(e){
e.preventDefault();
var navi = document.querySelector(".navigation");
var navi_ativo = navi.dataset.ativo;
navi.setAttribute("data-ativo", navi_ativo == "true" ? "false" : "true");
});
});
ul.navigation[data-ativo='false']{
display: none;
}
ul.navigation[data-ativo='true']{
display: block;
}
<div id="menu">
<a class="menuicon" href='#'>Menu</a>
<ul class="navigation" data-ativo="false">
<li><a href='#'>Home</a></li>
<li><a href='#'>Link 1</a>
<li><a href='#'>Link 2</a>
</ul>
</div>
There is another simpler approach. When the element is hidden with display: none
, its height is equal to 0
, with this you can switch between display: none
and display: block
checking whether the height is equal to 0
:
document.addEventListener("DOMContentLoaded", function(){
document.querySelector(".menuicon").addEventListener("click", function(e){
e.preventDefault();
var navi = document.querySelector(".navigation");
var navi_height = navi.clientHeight || navi.offsetHeight;
navi.style.display = navi_height ? "none" : "block";
});
});
.navigation{
display: none;
}
<div id="menu">
<a class="menuicon" href='#'>Menu</a>
<ul class="navigation">
<li><a href='#'>Home</a></li>
<li><a href='#'>Link 1</a>
<li><a href='#'>Link 2</a>
</ul>
</div>
As to the
toggle()
obsolete, usetoggleClass()
in place oftoggle()
.– Augusto Vasques
Hello, Augusto, I managed using the same toggleClass, it worked. I’ve been researching here and apparently this is the most used solution even. Thanks!
– Mari