For the past 48 hours, I've been grappling with the challenge of removing an added class from an Element. Despite scouring the internet for a solution, I haven't been able to find one.
I have successfully added a class to the navigation to display the submenu, which works perfectly fine.
However, when attempting to hide the menu upon a user click anywhere on the window, the code to remove the class fails to work. I am solely using Vanilla JS without relying on jquery as I aim to master JS independently first.
Your assistance would be greatly appreciated as I have been unable to find a resolution online!
https://jsfiddle.net/dx6ofnvs/4/
HTML
<nav>
<div class="nav__navigation">
<ul>
<li id="services__btn"> <a href="#"> Services</a></li>
<div class="services__dropdown__container">
<ul id="services__dropdown" class="dropdown">
<li> <a href="#"> Link One</a></li>
<li> <a href="#"> Link Two</a></li>
<li> <a href="#"> Link Three</a></li>
<li> <a href="#"> Link Four</a></li>
</ul>
</div>
</ul>
</div>
<div class="burger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
</nav>
CSS
const burger = document.querySelector(".burger");
const nav = document.querySelector(".nav__navigation");
const navLinks = document.querySelectorAll(".nav__navigation li");
const servicesBtn = document.querySelector("#services__btn");
const servicesDropdown = document.querySelector("#services__dropdown");
const servicesDropdownContainer = document.querySelector("#services__dropdown__container")
const html = document.querySelector("html")
///// Open Mobile Menu
burger.addEventListener("click", (navSlide));
function navSlide() {
nav.classList.toggle("nav-active");
}
///// Expand Dropdown Desktop View
servicesBtn.addEventListener("click", (e) => {
servicesDropdown.classList.add("dropdown--active");
})
window.addEventListener("click", (e) => {
if(e.target != servicesDropdown) {
/// The issue appears to lie within this particular code snippet where it removes the class immediately after being displayed.
servicesDropdown.classList.remove("dropdown--active")
console.log('clicked');
}
})