Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener to all but one element

I'm trying to wean myself off jQuery (my heart is in the right place, no?), and I'm having trouble getting to what would be the equivalent of the :not() selector.

I have document.body.addEventListener("mousewheel", scrollTriggered), which I want to fire on scroll of anything but a specific div (in the fiddle, #something). I've tried integrating event.target, to no avail.

Any help greatly appreciated. See JSFiddle

like image 445
emsoff Avatar asked Jun 11 '14 23:06

emsoff


1 Answers

You can check whether the event originated from within the element you want to avoid. To do that, you have to traverse up the DOM tree from target and compare each Node's id attribute, or use Node.contains (check the compatibility section first though):

var ignore = document.getElementById('something');

function scrollTriggered(event) {
    var target = event.target;
    if (target === ignore || ignore.contains(target)) {
        return;
    }
    // do other stuff
}

DEMO


That said, Markasoftware's answer is even better, since it prevents the event in the first place.

like image 126
Felix Kling Avatar answered Oct 20 '22 16:10

Felix Kling