CarbonCoder
CarbonCoder

Reputation: 35

Function parameters not working with .classList.add

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

Upvotes: 1

Views: 400

Answers (1)

Clarity
Clarity

Reputation: 10873

addEventListener expects a callback function, not a function call result (which happens in your case). Wrap your function in another function to fix the issue:

dropDown.addEventListener("mouseenter", () => toggleClass(dropDownList, classToToggle));
dropDown.addEventListener("mouseleave", () => toggleClass(dropDownList, classToToggle));

Upvotes: 2

Related Questions