Reputation: 77
Hi, the jQuery hover event not working for appended object via ajax .
I add <div class="item ..."> ... </div>
with
Ajax call:
var jqxhr = $.ajax( '{{ path('nextPage_url') }}'+page )
.always(function(data) {
$("#container").append(data).masonry('reload');
});
Hover Event delegation :
I have hovered over .item
class elements,it
works fine for preloaded data,but for new <div>
added via ajax request its not working
$('.item').hover(
function(){
$(this).addClass('img-polaroid-shadow').removeClass('img-polaroid');
},
function(){
$(this).removeClass('img-polaroid-shadow').addClass('img-polaroid');
}
);
Thanks
Upvotes: 1
Views: 2555
Reputation: 1353
Try below code
$(document).on('mouseover','span', function () {
$(this).css('color','#CCC');
});
$(document).on('mouseout','span', function () {
$(this).css('color','#000');
});
Working sample on jsFiddle http://jsfiddle.net/HpL7X/
Upvotes: 2
Reputation: 861
This is because when you applied the event handler and the page loaded, the elements which existed before were seen by JavaScript and thus it applied handlers to only those elements.
However, when you appended an item (element) to the page, it wasn't on the list of the DOM. Thus, you need to use Event Delegation in this case.
Simply use jQuery's .on()
or .delegate()
methods. If you want to know how it works then go here for a simple jQuery tutorial (not a reference, just a recommendation).
Upvotes: 2
Reputation: 14827
You need to use event delegation for dynamically added element, so:
$(document).on(
{
mouseenter: function()
{
$(this).addClass('img-polaroid-shadow').removeClass('img-polaroid');
},
mouseleave: function()
{
$(this).removeClass('img-polaroid-shadow').addClass('img-polaroid');
}
}
, '.item');
Upvotes: 2