1

I am using Infinite Scroll to display some content and I'm having trouble binding some mouseenter/mouseleave events to the newly generated items.

I know that I need to bind .on to a container already existing on the page, but I'm having trouble figuring out the syntax to alter the current jQuery that toggles.

This is the current js:

$(document).ready(function() {
    $('.grid-box .actions').hide();

    $('.grid-box').on({
        mouseenter: function () {
            $(this).find('.actions').show();
        },
        mouseleave: function () {
            $(this).find('.actions').hide();
        }
    });

});

The main container is #grid-container and each individual item is .grid-box. How can I alter the above so that the actions show/hide upon entering/leaving .grid-box?

I think I need something along the lines of this:

$('#grid-container').on('mouseenter mouseleave', '.grid-box', function(e) {

// some action

});
Motive
  • 3,071
  • 9
  • 40
  • 63
  • See these posts about using `.on()` with dynamic elements: http://stackoverflow.com/questions/9985090/jquery-on-does-not-work-but-live-does/9985137#9985137 and http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409 – jfriend00 Jan 07 '13 at 19:00

2 Answers2

3

Exactly, this is known as event delegation and it waits for the event to bubble up then matches the event based on the selector. This is much more efficient because there is only one handler registered rather than N times the number of elements. Also, you only have to bind once rather than every time the dynamic content is changed.

$('#grid-container').on('mouseenter', '.grid-box', function(e) {

    // some action

}).on('mouseleave', '.grid-box', function(e) {

    // some action

});
arhea
  • 454
  • 2
  • 5
1

The selector as the second argument will still work:

$('#grid-container').on({ ...}, '.grid-box');

http://jsfiddle.net/QkFTz/1/

An alternate method would just be to bind them separately, which I personally think is clearer:

$("#grid-container").on('mouseenter', '.grid-box', function () {})
   .on('mouseleave', '.grid-box', 'function () {});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405