jQuery animation on window load on an infinite loop?
I need a hand making this code below working. I've had it working so that when the user hovers over the image it animates up, then down when losing focus, but now I want it to run on window load on an infinite loop.
$(document).ready(function(){
$(window).load(function(){
$('.navImage').animate({top:'-=13'}, 700)
}, function(){
$('.navImage').animate({top:'+=13'}, 700);
});
});
At the moment it's only animating 13pixels up, not down, and obviously the animation doesn't currently loop. Do I need to use some sort of call开发者_Go百科back?
Any help would be great, thanks.
[EDIT] Removed the height:toggle, didn't mean to include that.
Try this:
function moveUp() {
$('.navImage').animate({top:'-=13', height:'toggle'}, 700, moveDown);
}
function moveDown() {
$('.navImage').animate({top:'+=13'}, 700, moveUp);
}
$(document).ready(function(){
$(window).load(moveUp);
});
=== UPDATE 1 ===
function move(jElem, bUp) {
jElem.animate(
{top: (bUp ? '-' : '+') + '=13'},
700,
function() {
move(jElem, !bUp);
}
);
}
$(document).ready(function() {
$(window).load(function() {
$('.navImage').each(function() {
move($(this), true);
});
});
});
Also see my jsfiddle.
=== UPDATE 2 ===
Now they start with random delay:
function move(jElem, bUp) {
jElem.animate(
{top: (bUp ? '-' : '+') + '=13'},
700,
function() {
move(jElem, !bUp);
}
);
}
$(document).ready(function() {
$('.navImage').each(function(iIndex, jElem) {
// get random delay
var iTime = Math.floor(Math.random() * 700);
setTimeout(
function() {
move($(jElem), true);
},
iTime
);
});
});
Also see my jsfiddle 2.
=== Update 3 ===
And in this jsfiddle additional with random speed: jsfiddle 3.
function anim_up() {
$('.navImage').animate({top:'-=13', height:'toggle'}, 700, anim_down)
};
function anim_down() {
$('.navImage').animate({top:'+=13'}, 700, anim_up);
};
window.onload = anim_up;
As a sidenote, you should replace that navImage
class with an ID instead, if there's only one of them.
精彩评论