Need guideline about random image rotation?

I am struggling to work out how to make all instances of images with the id=”cover__thumb” rotate randomly through the predefined images.

Currently only the first id=”cover__thumbs” will rotate, it has no affect on the other images with the same id.

Read More

There won’t always be 4 images, sometimes more sometimes less. Is there a solution that works for any image with the this id?

I am struggling to work out how to make all instances of images with the id=”cover__thumb” rotate randomly through the predefined images.

Currently only the first id=”cover__thumbs” will rotate, it has no affect on the other images with the same id.

There won’t always be 4 images, sometimes more sometimes less. Is there a solution that works for any image with the this id?

JS:

function rotateImages()
{
    var thumbImages = new Array( );

    thumbImages[0] = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg";
    thumbImages[1] = "http://cdn.images.express.co.uk/img/dynamic/13/590x/magnolia-tree-630524.jpg";
    thumbImages[2] = "http://cdn.images.express.co.uk/img/dynamic/109/590x/Oak-tree-580618.jpg";

    var image = document.getElementById('thumb__cover');
    var randomImageIndex = Math.floor( Math.random( ) * thumbImages.length );
    image.src = thumbImages[randomImageIndex];
}
window.setInterval(rotateImages, 1000);

HTML is

<img id="thumb__cover" src="https://www.hdmegawallpaper.com/wp-content/uploads/2016/05/image_20160511_005430_3370.jpg" style="width:150px;">
<img id="thumb__cover" src="https://www.hdmegawallpaper.com/wp-content/uploads/2016/05/image_20160511_005430_3372.jpg" style="width:150px;">
<img id="thumb__cover" src="https://www.hdmegawallpaper.com/wp-content/uploads/2016/05/image_20160511_005430_3373.jpg" style="width:150px;">
<img id="thumb__cover" src="https://www.hdmegawallpaper.com/wp-content/uploads/2016/05/fathers-day-wallpaper-1.jpg" style="width:150px;">

Related posts

1 comment

  1. To expand on my answer above:

    In HTML, the id tag should be unique per page. When you refer to something by id in javascript, it only expects to look for one element with that id. So, when you use javascript to do something to that id, it’s only going to do it to the first element with that id that it finds in the DOM.

    var image = document.getElementById('thumb__cover');

    This only gets the first image with that id. If there’s only one, it works fine, but if there’s more than one, it’s only going to do the rest of your code once.

    What you want to use is document.getElementByClassName()

Comments are closed.