Home > other >  How to create an event listener click to all window except one div
How to create an event listener click to all window except one div

Time:04-29

I have a div that contains a dropdown with multiple checkboxes.

I have these two event listeners:

widget.addEventListener("click", function (ev) { 

    if (checkboxes.style.display === "none") {
        checkboxes.style.display = "block"; 
    } else {
        checkboxes.style.display = "none"; //hide the dropdown
    }

    ev.preventDefault(); 
    ev.stopPropagation();
});
    
window.addEventListener("click", function (ev) { 

    if (checkboxes.style.display === "block") {
        checkboxes.style.display = "none";
    }

    ev.preventDefault();

});

These two work. When I click on the dropdown widget the dropdown opens and closes as expected.

The second event also works. When I click anywhere on the window the dropdown if open closes. The thing is that this dropdown has checkboxes, so a checkbox is part of the window as well. As I click on a checkbox to check it the dropdown closes instead of giving the user the possibility to select one or more checkboxes and after closes.

So the solution is definitely instead of window.addEventListener to do window(except dropdown div).addEventListener. I know the dropdown div id name so I can get it but what I don't know is how to create a event listener for that without the dropdown.

PS: In the code the checkboxes are just the dropdown and widget is the dropdown widget icon.

CodePudding user response:

this solved my issue

 document.body.addEventListener('click', function (e) {
    if (!e.target.classList.contains('dropdown-container')) {
        // your code
    }
});

Reference: https://stackoverflow.com/a/58837155/18600916

CodePudding user response:

Try using mouseup instead of click event

widget.addEventListener("mouseup", function (ev) { 

    if (checkboxes.style.display === "none") {
        checkboxes.style.display = "block"; 

    } else {
        checkboxes.style.display = "none"; //hide the dropdown
    }
}
ev.preventDefault(); 
ev.stopPropagation();
});

window.addEventListener("mouseup", function (ev) { 


    if (checkboxes.style.display === "block") {
        checkboxes.style.display = "none";
    }

ev.preventDefault();

});
  • Related