Reputation: 2110
I have horizontal set of 4 images. The resize function works on mouseover event. This means that if I move the mouse very fast or slow over these images they will All resize. Because of this I need the user to keep the mouse over for at least 1.5 sec over a given image and then proceed with the resize. This is the unproper code:
$('a img').mouseover(function(){
$(this).delay(1500).animate({
width: "315px",
height: "225px",
marginLeft: "-50px"
}, 1500 );
});
$('a img').mouseout(function(){
$(this).animate({
width: "210px",
height: "150px",
marginTop: "0px",
marginLeft: "0px"
}, 500 );
});
Upvotes: 2
Views: 1702
Reputation: 13496
you can use setTimeout and clearTimeout for this:
also .hover() is a shortcut method in jQuery to handle mouseOver and mouseOut at the same time.
var TimeoutHandler = 0;
var ImageToAnimate = null;
function AnimationIn()
{
// animate ImageToAnimate
}
function AnimationOut(image)
{
// animate image
}
$('a img').hover(function()
{
clearTimeout(TimeoutHandler );
ImageToAnimate = this;
TimeoutHandler = setTimeout(AnimationIn, 1500);
}, function()
{
AnimationOut(this);
});
Upvotes: 2
Reputation: 708016
I'm not sure of the exact logic you want, but here's one way to do it. I didn't hook up the actual animation, but rather just show you when it would trigger.
HTML:
<div class="container">
<img src="http://photos.smugmug.com/photos/227688911_f5X9o-Ti.jpg" border="0">
<img src="http://photos.smugmug.com/photos/231469043_zkRUp-Ti.jpg" border="0">
<img src="http://photos.smugmug.com/photos/227688911_f5X9o-Ti.jpg" border="0">
<img src="http://photos.smugmug.com/photos/231469043_zkRUp-Ti.jpg" border="0">
<img src="http://photos.smugmug.com/photos/227688911_f5X9o-Ti.jpg" border="0">
</div>
<div id="result">
</div>
JS:
(function() {
var myTimer = null;
function animate() {
$("#result").append("go, ");
}
$(".container").mouseenter(function() {
if (!myTimer) {
myTimer = setTimeout(function() {
myTimer = null;
animate();
}, 1500);
}
});
$(".container").mouseleave(function(){
if (myTimer) {
clearTimeout(myTimer);
myTimer = null;
}
});
}());
This could be made a tiny bit more foolproof by checking if the mouse was still over the iamges before firing the animation just in case the mouseleave event was missed somehow.
You can see it in action here: http://jsfiddle.net/jfriend00/9q36R/
Upvotes: 1
Reputation: 22339
I would use .setTimeout()
$('a img').mouseover(function(){
var imgElement = $(this);
var timeoutID = window.setTimeout(
function(){
imgElement.animate({
width: "315px",
height: "225px",
marginLeft: "-50px"
}, 1500 );
}, 1500);
imgElement.data("timeout", timeoutID);
});
$('a img').mouseout(function(){
var imgElement = $(this);
var timeoutID = imgElement.data("timeout");
window.clearTimeout(timeoutID);
$(this).animate({
width: "210px",
height: "150px",
marginTop: "0px",
marginLeft: "0px"
}, 500 );
});
Upvotes: 1