I have just started learning about event listeners and how to use them. Creating a new event listener from scratch seems easy enough. The problem is that I want to add an event listener to a previous code that relied on the html onclick solution.
In this case it is a navigation sidebar that I want to open and close when pressing a menu icon. When looking at my current js file, I have absolutely no clue where to place the event listener or how to make it link up with the code I already wrote.
I would be very thankful if someone could help me explain it to me and give me that “aha!” moment I have been looking for. 😁
THE HTML
`<body>
<nav class=”nav-main”>
<div class=”btn-toggle-nav”></div>
<ul>
<li><a href=”#”>menu1</a></li>
<li><a href=”#”>menu2</a></li>
<li><a href=”#”>menu3</a></li>
<li><a href=”#”>menu4</a></li>
</ul>
</nav>
<aside class=”nav-sidebar”>
<ul>
<li><span>menu1</span></li>
<li><a href=”#”>menu2</a></li>
<li><a href=”#”>menu3</a></li>
<li><a href=”#”>menu4</a></li>
</ul>
</aside>
</body>`
THE JAVASCRIPT
`let toggleNavStatus = false;
let toggleNav = function() {
let getSidebar = document.querySelector(“.nav-sidebar”);
let getSidebarUl = document.querySelector(“.nav-sidebar ul”);
let getSidebarTtitle = document.querySelector(“.nav-sidebar span”);
let getSidebarLinks = document.querySelectorAll(“.nav-sidebar a”);
if (toggleNavStatus === false) {
getSidebarUl.style.visibility = “visible”;
getSidebar.style.width = “272px”;
getSidebarTtitle.style.opacity = “0.5”;
let arrayLength = getSidebarLinks.length;
for (let i = 0; i < arrayLength; i++) {
getSidebarLinks[i].style.opacity = “1”;
}
toggleNavStatus = true;
}
else if (toggleNavStatus === true) {
getSidebar.style.width = “50px”;
getSidebarTtitle.style.opacity = “0”;
let arrayLength = getSidebarLinks.length;
for (let i = 0; i < arrayLength; i++) {
getSidebarLinks[i].style.opacity = “0”;
}
getSidebarUl.style.visibility = “hidden”;
toggleNavStatus = false;
}
}`