dotancohen
dotancohen

Reputation: 31471

Expanding divs returned via AJAX

Consider the following Javascript jQuery code for dynamically expanding a div:

$('.expandingThumbnail').hover(function() {
    $(this).animate({
        height: '32px',
        width:  '32px'
    }, 500);
},function() {
    $(this).animate({
        height: '128px',
        width: '128px'
    }, 500);
});

It is operating on any theoretical div:

<div class="expandingThumbnail">Hi!</div>

So long as this div is returned as part of the page request, it expands as expected. However, if this div is returned as part of an AJAX request and inserted into another div via jQuery's .html() method, then the div does not expand as expected. Why is this, and how might I work around it?

Upvotes: 0

Views: 116

Answers (1)

nbrooks
nbrooks

Reputation: 18233

This is the typical problem with dynamically generated content; direct event handlers only apply to elements which already exist when they are called. You need to bind your handler to a static parent element in order to handle the event triggered by new elements. See .on for details. Note that you can (and should) replace document below with a selector for the nearest, static parent element of .expandingThumbnail for improved performance.

$(document).on( 'mouseenter', '.expandingThumbnail', function() {
    $(this).animate({
        height: '32px',
        width:  '32px'
    }, 500);
}).on('mouseleave', '.expandingThumbnail', function() {
    $(this).animate({
        height: '128px',
        width: '128px'
    }, 500);
});

Upvotes: 2

Related Questions