jqueryjquery-onjquery-delegate

how to attach hover handler to TD elements, filtering on a class selector that may be applied in the future


My table will have a number of TD elements that get assigned a class, .foo, during the course of the user working with the data. The table might have a few hundred cells and only a dozen of those may acquire the .foo class. I want to listen for hover on those particular TD elements. It looks as though the delegate() method in jQuery listens for javascript events, whereas hover is a jQuery event, is that right? How to create a delegate to listen for hover on TD.foo elements that will have the .foo class assigned to them in the future?


Solution

  • delegate is not recommended for use in newer jQuery, you should use on

    As of jQuery 1.7, .delegate() has been superseded by the .on() method.

    $('#table').on('mouseenter mouseleave', 'td.foo', function(e) {
        if(e.type === 'mouseenter') {
            //hover in
        } else {
            //hover out
        }
    });