1

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

3
  • 1
    Your calls to .addEventListener() are wrong. Your code calls the toggleClass() function and passes the return value to .addEventListener(). You have to wrap the calls to toggleClass() in another anonymous function. Commented Sep 18, 2019 at 12:13
  • Is there a specific reason why this has to be done with JavaScript? jsfiddle.net/rsgz8wcv Commented Sep 18, 2019 at 12:16
  • Doing this in Javascript purely for learning purposes, appreciate the CSS answer though. Commented Sep 18, 2019 at 12:25

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.