I have created a simple function to remove and add classes but I cannot get it to work, below is the html to test on, it needs to work so that when the mouse enters '.dropdown' then #myDropdown will get a class added to it 'show' and when the mouse leaves then the class will be removed:
const dropDown = document.querySelector('.dropdown');
const dropDownList = dropDown.querySelector('#myDropdown');
const classToToggle = 'show';
dropDown.addEventListener("mouseenter", toggleClass(dropDownList, classToToggle));
dropDown.addEventListener("mouseleave", toggleClass(dropDownList, classToToggle));
function toggleClass(target, className) {
if(target.classList.contains(className)) {
target.classList.remove(className);
} else {
target.classList.add(className);
}
}
<div class="dropdown">
<a href="javascript:void(0)" class="dropbtn" style="outline: none;">Dropdown <i class="fas fa-chevron-down"></i></a>
<div id="myDropdown" class="dropdown-content">
<p>Item 1</p>
<p>Item 2</p>
<p>Item 3</p>
<p>Item 4</p>
</div>
</div>
The function just isn't adding 'className' to the 'target' even though when I console.log the 'className and 'target' parameters they both seem to have come through okay.
Thanks
.addEventListener()are wrong. Your code calls thetoggleClass()function and passes the return value to.addEventListener(). You have to wrap the calls totoggleClass()in another anonymous function.