Reputation: 152
How do you remove a document.addEventListener()
? In the fiddle below if you click the 'Dropdown Button' and then click outside the menu, multiple click events continue to fire (see console). I want to be able to hide the menu when clicking anywhere outside of it. I know I need to remove the event listener but I don't know how.
I've tried using a named function e.g.
document.addEventListener('click', myFunct);
However I can't pass any arguments to the parameters inside myFunct
and I've also tried using .bind()
with no success e.g.
document.addEventListener('click', myFunct(event, dropdownMenu));
document.addEventListener('click', myFunct.bind(event, dropdownMenu));
https://jsfiddle.net/shc3ek02/1/
let dropdownBtn = document.querySelectorAll('.dropdown-trigger .button');
let initDropdown = function (event) {
let dropdownMenu = event.target.closest('.dropdown');
openDropdown(dropdownMenu);
closeDropdown(dropdownMenu);
}
let openDropdown = function (dropdownMenu) {
dropdownMenu.classList.add('is-active');
}
let myFunct = function(dropdownMenu) {
if (!dropdownMenu.contains(event.target)) {
dropdownMenu.classList.remove('is-active');
console.log(event.target);
}
}
let closeDropdown = function (dropdownMenu) {
// works but fires multiple click events
// document.addEventListener('click', function (event) {
// if (!dropdownMenu.contains(event.target)) {
// dropdownMenu.classList.remove('is-active');
// console.log(event.target);
// }
// });
// this doesn't work
document.addEventListener('click', myFunct(dropdownMenu));
}
dropdownBtn.forEach(function (button) {
button.addEventListener('click', initDropdown);
});
Thanks in advance
Upvotes: 0
Views: 74
Reputation: 684
Take a look at element.removeEventListener(event, function)
(https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener, https://www.w3schools.com/jsref/met_element_removeeventlistener.asp)
Upvotes: 3