Is it possible to add a hover effect (animation) to AJAX loaded content/images? Currently I'm using this code to do it, but it only works for the images that are loaded without AJAX.
$(".box img").each(function() {
$(this).hover(function() {
$(this).stop().animate({ opacity: 1.0 }, 500);
},
function() {
$(this).stop().animate({ opacity: 0.3 }, 500);
});
});
Live Events or Delegates are the way to go:
$('.box').delegate('img', {
mouseenter: function() {
$(this).stop().animate({ opacity: 1.0 }, 500);
},
mouseleave: function() {
$(this).stop().animate({ opacity: 0.3 }, 500);
}
});
By the way, in your original code there was no need to use each
- you could have used $('.box img').hover(...)
Use .delegate
$('.box').delegate('img', {
mouseover: function (e) {
$(this).stop().animate({ opacity: 1.0 }, 500);
},
mouseout: function (e) {
$(this).stop().animate({ opacity: 0.3 }, 500);
}
});
$('.box').delegate('img', {
mouseenter: function() {
$(this).stop().animate({ opacity: 1.0 }, 500);
},
mouseleave: function() {
$(this).stop().animate({ opacity: 0.3 }, 500);
}
});
is better than live
You'll get better performance using jQuery's .delegate()
rather than .live()
.
$('.box').delegate('img','hover', function( event ) {
if( event.type === 'mouseenter' )
$(this).stop().animate({ opacity: 1.0 }, 500);
else
$(this).stop().animate({ opacity: 0.3 }, 500)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.