javascriptjqueryjquery-eventsmouselistener

Using one listener instead of hundreds


Right now I have this, and it works:

$(document).on('mouseenter', 'td', mouseEnter)
function mouseEnter() {
}

But I think that's attaching an event listener to every table cell.

Q: How could I write it so that it only uses one listener?


Solution

  • That is one listener. This code would attach to every table cell:

    $("td").on("mouseenter", function(e) {
        //do stuff
    });
    

    Your code is correct. Effectively, what happens is the mouseenter event "bubbles" up through the DOM until it his the top, which is the "document". When it gets there, your code inspects to see where the event came from, and only fires if it's a TD element.

    This is especially good because it still applies even if you add a new TD to your document - this listener will pick up mouseenter events without you needing to do another "on".