I want to close the menu when I click on a link. Do you have an idea why my code does not work? jsbin
document.getElementById("menu").addEventListener("click",function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log("ok");
menu.style.display = "none";
}
});
<ul class="nav__right" id="menu">
<li>
<h3><a href="#home">home</a></h3>
</li>
<li>
<h3><a href="#about">À propos</a></h3>
</li>
<li>
<h3><a href="#production">Réalisations</a></h3>
</li>
<li>
<h3><a href="#contact">Contact</a></h3>
</li>
</ul>
e.target.nodeName returns A whereas you are comparing it with LI.
document.getElementById("menu").addEventListener("click",function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "A") {
console.log("ok");
this.style.display = "none";
}
});
<ul class="nav__right" id="menu">
<li>
<h3><a href="#home">home</a></h3>
</li>
<li>
<h3><a href="#about">À propos</a></h3>
</li>
<li>
<h3><a href="#production">Réalisations</a></h3>
</li>
<li>
<h3><a href="#contact">Contact</a></h3>
</li>
</ul>
You have two silly mistakes. First, menu is an undefined variable. You obviously meant document.getElementById('menu'). Last, the nodeNamemethod will return "A", not "LI". Here is the corrected code:
document.getElementById("menu").addEventListener("click",function(e) {
if(e.target && e.target.nodeName == "A") {
console.log("ok");
this.style.display = "none";
}
});
<ul class="nav__right" id="menu">
<li>
<h3><a href="#home">home</a></h3>
</li>
<li>
<h3><a href="#about">À propos</a></h3>
</li>
<li>
<h3><a href="#production">Réalisations</a></h3>
</li>
<li>
<h3><a href="#contact">Contact</a></h3>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With