Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery syntax for multiple delegated events

Tags:

jquery

The jQuery docs at http://api.jquery.com/on/ mention the benefits of delegated-events using the following syntax (which attaches an event handler to only one element):

$('#mytable').on('click', 'tr.hoverable', function(){
    // blah
});

But I can't find any reference to proper syntax for attaching multiple events at once WITH delegated-events. Is there a shortcut for the following, but with tr.hoverable as a delegated event?

$('#mytable tr.hoverable').on({
    mouseenter: function(){
        // blah
    },
    mouseleave: function(){
        // blah
    },
    click: function(){
        // blah
    }
});

Or is this the only solution ...

$('#mytable').on('click', 'tr.hoverable', function(){
    // blah
}).on('mouseenter', 'tr.hoverable', function(){
    // blah
}).on('mouseleave', 'tr.hoverable', function(){
    // blah
});

?

like image 998
neokio Avatar asked Jun 12 '12 11:06

neokio


1 Answers

$('#mytable').on({
    mouseenter: function(){
        // blah
    },
    mouseleave: function(){
        // blah
    },
    click: function(){
        // blah
    }
}, '.hoverable');

As per this signature:

.on( events-map [, selector] [, data] )

Also, prefer single tagName/className/id selectors for delegation as they get optimized

like image 194
Esailija Avatar answered Oct 14 '22 19:10

Esailija