The easiest way is probably to set an addEventListener
with the third argument to false
that does the action, and then have another addEventListener
on the element you want to exclude, with a third argument true
, which will cancel the event from propagating to the other event listener. The third argument is a little complicated, but the important part is that if it's set to true
, that listener will fire before any false
handlers. As @FelixKling said, you actually don't need it to be true
here, but it's good practice to do it whenever you need a handler to fire before another one, because sometimes it IS needed. Here's a jsfiddle example: http://jsfiddle.net/markasoftware/sBg3a/2/
document.body.addEventListener("mousewheel", scrollTriggered,false);
function scrollTriggered() {
console.log('hi');
}
document.getElementById('something').addEventListener('mousewheel',function(e) {
e.stopPropagation();
}, true);
Although @FelixKling's answer works, I personally think this is more elegant and generally use things like this instead of the other way. I just like how you can have the main event listener just have the listener code, and all the stuff that cancels the event from propagating can be completely separate, making it more unobstrusive