-1

I’m trying to find a way of playing a cycle of images and hyperlinks via JS or CSS (not sure which would work), in a similar fashion to how a GIF animation functions.

I would ordinarily use a GIF for something like this, but I’m wanting to randomise the order the images are shown with each page refresh (plus I wouldn’t know how to have different hyperlinks for specific frames in a GIF).

Thank you very much, I hope this makes sense

2

1 Answer 1

-2

You can do something like this with JavaScript:

var index=0;
var images = document.getElementsByClassName("slideshow");
    function changeBanner() { 
      [].forEach.call(images, function (v,i) {
          images[i].hidden = i!==index
      });
      index = (index+1) % images.length;
    }
window.onload = function() {
    setInterval(changeBanner, 1000)
};

And your HTML looks like this:

<img src="1.png" width="640px" height="480px" class="slideshow" />
<img src="2.png" width="640px" height="480px" class="slideshow"  />
<img src="3.png" width="640px" height="480px" class="slideshow"  />
<img src="4.png" width="640px" height="480px" class="slideshow"  />

This increments i each second, and removes the hidden attribute from the <img> element with the src of i.png.

Sign up to request clarification or add additional context in comments.

5 Comments

I didn't say anything when I down-voted this, but now that it's been accepted I must point out that this code is far from optimal. First and foremost, it assumes that every image in the document should be part of the playback. At least assume an array of images other than document.images or if that is not deemed necessary, declare a variable to refer to document.images instead of referring directly to document.images 3 separate times.
@GeorgeJempty OK, I'll change it, will you upvote me if it's better, or at least remove the downvote?
Yes that's better
This code works well for me, but I was wondering if it would be possible to randomise the order in which the images are displayed on every page reload? At the moment it always play in the same sequence
Maybe use Math.random to call a random index from an array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.