Reputation: 945
Im trying to animate an element while the user overs a link
var i = 0;
function next(){
while (i>-10) {
i--;
$('#conteudo').animate({left:"'"+i+"px'"},'slow');
};
}
$('#next').hover(function(){
next();
});
but its instantly incrementing the value -10.. im trying to do something like this: -1..-2..-3..-4.. until it get to -10. Can I control the delay before it increments?
what im doing wrong?
here's the link for jsfiddle http://jsfiddle.net/KwhSg/
Upvotes: 1
Views: 552
Reputation: 4102
you can use the setTimeout function
http://www.w3schools.com/jsref/met_win_settimeout.asp
just use that to increment your animation values at a given interval
Since this still isn't resolved, here's a solution. You can change the timeout / animation speed as necessary.
var i =10;
function next(){
$('#conteudo').animate({left:"-=10"},'slow');
}
$('#next').hover(function(){
while (i>0){
i--;
setTimeout(next(),1000);
}
});
Upvotes: 0
Reputation: 24362
Like another answerer pointed out, animate
is designed to take care of this for you. But for the sake of learning, here's how to do what you're trying to do:
var i = 0;
function next(){
$('#conteudo').css({left:"'"+i+"px'"});
// use setTimeout to pause for 30 milliseconds and let the view update
if (i-- > -10) setTimeout(next, 30);
}
$('#next').hover(function(){
next();
});
You need to use setTimeout
instead of a while loop. It pauses (30 milliseconds in this case) between iterations so that the view can update.
In your original attempt, as long as the while loop is executing, it has total control of the process, so the view can't update until the loop is finished. Once the loop is finished, it's already done decrementing i
, so you don't get any animation.
Upvotes: 2
Reputation: 6933
You could have set a boolean variable that can be set on your "hover over" event to true, and false on your "hover out" event, so your while loop would be like so
function next(){
while (i>-10 && !notHovered) {
i--;
$('#conteudo').animate({left:"'"+i+"px'"},'slow');
};
}
Upvotes: 2
Reputation: 58615
I guess you misunderstood what animate
does. Try replacing the whole thing by this:
$('#next').hover(function(){
$('#conteudo').animate({left:'-=10'},'slow');
});
Animate
already takes care of the animation, delays, the works.
Upvotes: 5