Reputation: 3
I'm building a site and I wish to have an image that once clicked it is replaced by another image and, on a second click, replaced by a third image an so on.
I've written a JavaScript function for this. The problem is that I can only call out one item on my index list, it never allows me several clicks to go trough all of my index items.
This is the code I've written so far:
function change (index) {
var links = new Array();
links[0] = img/videoplace.jpg;
links[1]="img/hiroshima.jpg";
var image = document.getElementById('social');
image.src = links[index];
}
<div class="box box1">
<img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)" >
</div>
Writing in the Html <img class="textOverImage" src="img/beehive.jpg" alt="social logo" id="social" onclick= "change(0); change(1)">
just causes the image to be replaced by the one corresponding to change(1)
on first click.
Really appreciate any help that can be given.
Upvotes: 0
Views: 2822
Reputation: 370689
Attach the event handler properly using Javascript instead (inline handlers are widely considered to be poor practice, and they're difficult to manage). Then, in the Javascript, you can keep a persistent variable of the current image index that's being displayed. On every click, increment the index, and display the appropriate image:
const links = [
'img/beehive.jpg', // first image is already displayed when page is loaded
'img/videoplace.jpg',
'img/hiroshima.jpg'
];
let index = 0;
const img = document.querySelector('#social');
img.addEventListener('click', () => {
index++;
img.src = links[index];
});
Note that declaring an array all at once is often nicer and more concise than using new Array()
and assigning to indicies one-by-one.
If you want the displayed images to wrap around so that, once the last image is clicked on, the first image is displayed again, then use modulo. Instead of
index++;
do
index = (index + 1) % links.length;
Upvotes: 1