00 Votes

JavaScript: Change Image and Link every X Seconds

Question by Alaska1966 | 2016-01-23 at 11:53

I would like to include some images on my homepage and those images should change each 10 seconds. However, I would also like to provide some links with the images, so that each image has an own link that should also change with the image exchange.

I have already created some JavaScript code for changing the images, but I do not know how to manage the link thing.

Here is my JavaScript for changing the images:

<script type="text/javascript">
  var x = 10; // seconds
  var images = ["img/img1.jpg", "img/img2.jpg" , "img/img3.jpg"];
  var index = 1;

  setInterval(function() {
    document.getElementById("main-image").src = images[index];
    index = (index + 1) % images.length;
  }, x * 1000);
</script>

Here is my HTML for displaying the images:

<img id="main-image" src="img/img1.jpg">

I do not know whether this is a step in the right direction, but I think it is.

ReplyPositiveNegative
0Best Answer0 Votes

Next to the images, you can also write the links into an array in order to change the links at the same time you are changing the images.

For example, you can extend your code in the following way:

var x = 10; // seconds
var images = ["img/img1.jpg", "img/img2.jpg", "img/img3.jpg"];
var links = ["link1.htm", "link2.htm" , "link3.htm"];
var index = 1;
 
setInterval(function() {
  document.getElementById("main-image").src = images[index];
  document.getElementById("main-link").href = links[index];
  index = (index + 1) % images.length;
}, x * 1000);

Of course, you have to ensure that there are the same number of links and images (the arrays must have the same length) and the order must fit (first element in the image array have to fit to the first element in the link array and so on).

The HTML can be adjusted in that way:

<a id="main-link" href="link1.htm">
   <img id="main-image" src="img/img1.jpg">
</a>

As you can see, the ID "main-link" is used to set the link and the ID "main-image" is used to set the appropriate image.
2016-01-23 at 12:04

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.