views:

45

answers:

4

I've five images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?

+2  A: 

Jquery Cycle is really flexible... you could hook it up to whatever youve got already marked up pretty easily.

prodigitalson
Is there any way to do it in JavaScript without using jQuery?
Mayur
Sure, i mean jQuery is just a javascript library. Its just more time consuming and is bound to me be more prone to error. Im sure if you search for `javascript slideshow` you'll find some tutorials on implementing something similar but its not going to have the flexibility youll get out of the box with Cycle or something similar based on a different library like PrototypeJS.
prodigitalson
Oh.. sorry i think we all missed your `homework` tag.
prodigitalson
+2  A: 

Simple javascript example:

var currentImage = 0;
var images = [
    'a.jpg',
    'b.jpg'
];
var imageElement = document.getElementById('yourImageTagId');

function nextImage(){
    currentImage = (currentImage + 1) % images.length;
    imageElement.src = images[currentImage];
}

var timeoutId = setTimeout(nextImage, 1000);

It expects you to have some html like this:

<img src="a.jpg" id="yourImageTagId" />
WoLpH
Is there any way to do it in JavaScript without using jQuery?
Mayur
@Mayur: I've added an example on how to do it without jQuery. Do note that I haven't tested it so you might need to debug before it works ;)
WoLpH
Sure! Thank you..
Mayur
nice example! Just remember that using a throughly tested library such as JQuery would allow you not only work faster but ensure that it works across different browsers.
Helmut Granda
@Helmut Granda: You are correct that jQuery is usually a better solution. However, code as simple as this will work just as well in all modern browsers.
WoLpH
@WoLpH. I agree with you but there are times when a solution is not good enough by just working on "modern browsers"
Helmut Granda
+1  A: 

There are many ways to do this nowadays but one simple way is using the following jquery plugin:

http://jquery.malsup.com/cycle/

Here is a simple demo in action fading images one after the other.

http://jquery.malsup.com/cycle/basic.html

Helmut Granda
Is there any way to do it in JavaScript without using jQuery?
Mayur
A: 

setTimeout

You can do something like this.

function selectData(currentIndex) {
    // select current's element "display" to "none" and show next element
    ...

    // schedule next change in two second        
    setTimeout("selectData(" + nextIndex + ");", 2000);
};

I assume all images are inside that div already and have style display:none

Nikita Rybak