Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain javascript equivalent of $(document).on(event) with selector

I'm trying to convert a jQuery event handler to pure javascript. There are loads of a particular selector on the page, so this was designed with only one event targeting document with that selector:

$(document).on("click", selectorString, function(event) {
 // do stuff
});

Where selector is a list of selectors as a string ".one, .two, .three".

I'm struggling to replicate this without jQuery though:

document.addEventListener("click", function(event){
    if (elementHasClass(event.target, selectorString) {
        // do stuff
    }
});

But this doesn't have the desired behaviour, as the listener is only on the document element, rather than the selected element within the document. Can anyone help with this?

like image 674
babbaggeii Avatar asked Nov 20 '15 15:11

babbaggeii


1 Answers

It seems like your problem is that it doesn't work on nested elements.

For instance, if you click on a nested span element that has a parent with the specified class, then it doesn't work because you are merely checking to see if the span element (which is event.target) has the class.

To resolve this, you could essentially delegate the event and check to see if any of the event.target element's parent's elements have the specified class:

Example Here

document.addEventListener("click", function (e) {
    var target = e.target;

    while (target && target.parentNode !== document) {
        target = target.parentNode;
        if (!target) { return; } // If element doesn't exist

        if (target.classList.contains('target')){
            // do stuff
            console.log(e.target);
        }
    }
});
like image 80
Josh Crozier Avatar answered Oct 27 '22 18:10

Josh Crozier