DEV Community

Dima Kuzmich
Dima Kuzmich

Posted on • Originally published at Medium on

Binding event to all elements except specific element and all its contents.

Recently I’ve encountered a challenge to close navigation menu on every touch or click, except clicks and touches in the menu area. I’ve tried many ways to resolve it, and at last, I’ve found the optimal solution for me. The solution is in two steps and relies on event bubbling.

Firstly, I’ve attached a click/touch event on the

that on every click/touch closes the menu.
function clickOnBody(event){
 // you can close here the menu
 alert(‘clicked everywhere except the menu area’);
}
document.body.addEventListener(‘mousedown’, clickOnBody, false);
document.body.addEventListener(‘touchstart’, clickOnBody, false);

Secondly, I’ve attached another click/touch event on a specific element, and inside this event, I’ll prevent event propagation (bubbling), so that every click/touch inside element area will stop on the parent element.

function clickOnMenu(event){
 event.stopPropagation();
}
var menu = document.getElementById(‘menu’);
menu.addEventListener(‘mousedown’, clickOnMenu, false);
menu.addEventListener(‘touchstart’, clickOnMenu, false);

You can check the solution in jsFiddle


Top comments (0)