Reputation: 131
How can I add a timer to my script? I want the "mouseenter" function to wait 1 second before launching.
$(".products_grid li").mouseenter(function(){
var $activeImage = $(this).find("img").attr("src");
var $imgZoom = '<div class="imgzoom"><img src="'+$activeImage+'" width="" height=""></div>';
$($imgZoom).hide().appendTo(this).fadeIn();
}).mouseleave(function(){
$("div.imgzoom").fadeOut().remove();
})
Upvotes: 0
Views: 136
Reputation: 23806
Use JavaScript's setTimeout, wrapping your code in another anonymous function, proxied to pass the current this
reference:
$(".products_grid li").mouseenter(function(){
$.proxy(setTimeout, this, function(){
var $activeImage = $(this).find("img").attr("src");
var $imgZoom = '<div class="imgzoom"><img src="'+$activeImage+'" width="" height=""></div>';
$($imgZoom).hide().appendTo(this).fadeIn();
}, 1000);
}).mouseleave(function(){
$("div.imgzoom").fadeOut().remove();
})
Upvotes: 2
Reputation: 318182
$(".products_grid li").on({
mouseenter: function () {
var self = this;
$(this).data('timer',
setTimeout(function() {
var activeImage = $(self).find("img").attr("src"),
imgZoom = $('<div />', {'class':'imgzoom'}),
img = $('<img />', {src:activeImage});
imgZoom.hide().append(img).appendTo(self).fadeIn();
}, 1000)
);
},
mouseleave: function () {
clearTimeout($(this).data('timer'));
$("div.imgzoom").fadeOut(function() {
$(this).remove();
});
}
});
Upvotes: 1
Reputation: 55740
Use setTimeout method
Encase your code inside the method and assign that to a variable.
Then clear the timeout on mouse leave.
var timer;
$(".products_grid li").mouseenter(function () {
var $activeImage = $(this).find("img").attr("src"),
$imgZoom = '<div class="imgzoom"><img src="' + $activeImage + '" width="" height=""></div>',
that = this;
timer = setTimeout(function () {
$($imgZoom).hide().appendTo(that).fadeIn();
}, 1000);
}).mouseleave(function () {
if (timer) {
clearTimeout(timer);
}
$("div.imgzoom").fadeOut().remove();
})
Upvotes: 2