Reputation: 51
I'm trying to create a "hover" effect with jQuery. It works fine except for a strange lag occuring only the first time the complete callback is called - I noticed it is the only time it actually reaches the exact position it should (rest are ~1px less, but that's fine), stays there for a bit, then continues the animation and from that point it works smoothly.
I've created a jsFiddle with my code here and this is the code I've written.
function hover(el, speed, start, stop) {
if (el.is(':visible')) {
el.animate({
'top': stop + 'px'
}, speed, function () {
el.animate({
'top': start + 'px'
}, speed, hover(el, speed, start, stop));
});
}
}
$("div > div").fadeIn(1000, function () {
hover($(this), 1000, 192, 210);
});
Am I missing something obvious? Is it a bug? Am I misusing something?
Any help appreciated, thanks!
Upvotes: 1
Views: 111
Reputation: 602
the lag is caused because in the second call of the hover() function your element is already in top: 210px so it just wait 1sec for nothing , to fix this just switch start and stop points in your function
function hover(el, speed, start, stop) {
if (el.is(':visible')) {
el.animate({
'top': start + 'px'
}, speed, function () {
el.animate({
'top': stop + 'px'
}, speed, hover(el, speed, start, stop));
});
}
}
so the lag will be in the start and won't get noticed
EDIT
a workaround is to give it a kick in the first time :
var firstTime = true ; //this is global
function hover(el, speed, start, stop) {
if (el.is(':visible')) {
el.animate({
'top': start + 'px'
}, speed, function () {
if(firstTime){
el.animate({'top' : stop +"px" } , speed , function(){
//something here
});
firstTime = false;
}
el.animate({
'top': stop + 'px'
}, speed, hover(el, speed, start , stop));
});
}
}
Upvotes: 1
Reputation: 2244
You can do this with CSS Animations
@-webkit-keyframes oscillation {
from { top:192px; }
to{ top:210px; }
}
@-moz-keyframes oscillation {
from { top:192px; }
to{ top:210px; }
}
Following that just put this in your CSS for div > div
:
-webkit-animation: oscillation 1s ease-in-out infinite alternate;
-moz-animation: oscillation 1s ease-in-out infinite alternate;
Upvotes: 1