I have 2 arrays,I with images and another with links. Using set interval I am changing the image in 2000millisec. How can I hyperlink the image with the links.

var img_array = <?php echo json_encode($images); ?>;
var link_array = <?php echo json_encode($links); ?>;
    var image = document.getElementById("aaa");
    var index=0;
function slide(){
    document["aaa"].src = img_array[index];
    index++;
    if(index>=img_array.length)
    {
    index=0;
    }
}
setInterval("slide()",2000);
    </script>

1 Answers

0
golddragon007 On

Here's an example. It's not perfect, because if you see it in the first time, the image is not loaded. This is why most of the sites generates all the images with links, and then just hide and show them.

var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
var link = document.getElementById("link");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;

function slide(){
    image.src = img_array[index];
    link.href = link_array[index];
    index++;
    
    if(index >= img_array.length) {
      index=0;
    }
}

setInterval(slide, 2000);
<a href="index1.html" id="link"><img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200"></a>

Or if you can't change the DOM or you want to hide somewhy the url you can do something like this:

var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;

function slide(){
    image.src = img_array[index];
    index++;
    
    if(index >= img_array.length) {
      index=0;
    }
}

image.addEventListener("click", function() {
    // This is because of the sandbox environment.
    console.log(link_array[index]);
    // This is what you need.
    window.open(link_array[index]);
});

setInterval(slide, 2000);
.pointer {
  cursor: pointer;
}
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200">

However in this case maybe you will get blocked by the browser or if the click was registered after the new image was loaded, it may create a missclick.