Reputation: 124
I am trying to make simple effects to the menu with Jquery hover. Here is my Javascript:
$(".goodi").hover(function () { // make width 50px on mousenter
elemin = this;
$(elemin).animate({
"height": "50px"
}, 1000);
}, function () {
elemout = this;
setTimeout(function () { // restore width to 100px in 1 second after mouseleave
$(elemout).animate({
"height": "100px"
}, 1000);
}, 1000);
});
And here is html and CSS just for demo:
.goodi {
background:lightgrey;
width: 100px;
height:100px;
float:left;
margin:10px; }
<div class="goodi"></div>
<div class="goodi"></div>
<div class="goodi"></div>
Here is jsfiddle.
The problem I have and spent whole day trying to fix it: when I hover fast enough on all of .goodi divs, they change their height, but only the last one hovered restores it back to 100px. setTimeout must work for each div hovered, but it doesnt.
Any ideas? Thanks much.
Upvotes: 0
Views: 131
Reputation: 61
Also if user is very happy you don't want the OUT animation to be triggered everytime
$(".goodi").each(function () {
var timer;
$(this).hover(function () {
clearTimeout(timer);
var elemin = this;
$(elemin).stop().animate({
"height": "50px"
}, 1000);
}, function () {
var elemout = this;
clearTimeout(timer);
timer = setTimeout(function () {
$(elemout).stop().animate({
"height": "100px"
}, 1000);
}, 1000);
})
});
Upvotes: 1
Reputation: 9583
you need to define the variables elemin
and elemout
locally
$(".goodi").hover(function () {
var elemin = this;
$(elemin).animate({
"height": "50px"
}, 1000);
}, function () {
var elemout = this;
setTimeout(function () {
$(elemout).animate({
"height": "100px"
}, 1000);
}, 1000);
});
Upvotes: 3