I'm trying to make a Script that when a user clicks in an image with the class "burger-nav-img" it toggles the class "open" in another elements. My code is:
HTML
<nav class="main-nav">
<ul class="flex-container">
<li class="flex-content"><a href="#">Home</a></li>
<li class="flex-content"><a href="#">Articles</a></li>
<div class="logo_container flex-container">
<img src="img\logo_background.png" class="logo flex-content">
</div>
<li class="flex-content"><a href="#">Support</a></li>
<li class="flex-content"><a href="#">Login</a></li>
</ul>
<a class="burger-nav">
<img src="img/menu.png" id="burger" class="burger-nav-img">
</a>
JavaScript
document.body.addEventListener("load", clas);
function clas() {
document.getElementsByClassName("burger-nav-img").addEventListener("load", toggl);
}
function toggl() {
const burger = document.getElementsByClassName("burger-nav");
burger.classList.toggle("open");
const main = document.getElementsByClassName("main-nav");
main.classList.toggle("open");
}
The problem is that when I run this code an error appears and I can't figure out what to do:
Console
menu.js:7 Uncaught TypeError: Cannot read property 'toggle' of undefined
at toggl (menu.js:7)
at clas (menu.js:3)
at menu.js:1
toggl @ menu.js:7
clas @ menu.js:3
(anonymous) @ menu.js:1
Note: menu.js is the file containing the JavaScript Code;
What should I do? Thank You For Your Attention!
addEventListeneris incorrect. You're passing the result of callingclass()instead of just a reference to the function (claswithout the()).