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

Dima Kuzmich
1 min readMay 28, 2014

--

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 rely on event bubbling.

Firstly, I’ve attached click/touch event on the <body> 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 specific element, and inside this event I’ll prevent event propagation (bubbling), so that every click/touch inside element area will stop on the parrent 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

--

--