I'm trying to build a picture slider. (I know there are tons of plug-ins out there, but this is more for educational purposes).
Basically, I have a set of images with z-index: 0. What I am trying to do is take the set of images, then select each one of the images and change the index to 1, animate the opacity, and then put it back at 0, so that the next image will do the same thing.
This is the first part, but the problem I have is that when I am testing this part, all the images do the animation at the same time. Instead of doing one after the other. I know that you can use callback functions such as:
image1.animate(the animation, function({
image2.animation(the animation, function({
image3.animation(the animation, function}) etc...
})
But if I had more images it would become more complicated. I am trying to find a more efficient way of doing this, but I am not finding the answer.
This is what I have tried:
images.each(function () {
$(this).css({
"opacity" : "0.0",
"z-index" : "1"
}).animate({
opacity: "1.0"
}, 3000);
});
but it doesn't work. All the images do the animation at the same time. I even tried with a "for" loop, but I get the same thing:
for (var i=0; i<images.length; i++){
images.eq(i).css({
"opacity" : "0.0",
"z-index" : "1"
}).animate({
opacity: "1.0"
}, 3000);
}
I know I am doing something wrong, but I can't figure out what it is. If anyone has any help it would be greatly appreciated!
The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);
The animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality. Note: Not all CSS properties are animatable.
jQuery height() Method The height() method sets or returns the height of the selected elements.
The animate() method performs a custom animation of a set of CSS properties.
Use a .delay()
, like this:
images.each(function (i) {
$(this).delay(3000*i)
.css({ opacity : 0, "z-index": 1 })
.animate({ opacity: 1 }, 3000);
});
Since this uses the index of the element passed as the first parameter to the .each()
callback the first is delayed 3000*0
ms, so not at all, the second delays for 3000ms, etc...so they animate one after the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With