0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ana
  • 3
  • 2

1 Answers1

1

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;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • First of all, thank you for your time! Though I still may be doing something wrong in my html because now I can't even click the image... – Ana Nov 09 '18 at 11:49
  • JAVASCRIPT: HMTL:
    social logo
    Once again, thank you
    – Ana Nov 09 '18 at 11:51
  • Open your browser console and look for errors. If the code is in the order you described, you aren't running the script at the right time - you need to wait for the element to exist before attaching the handler. See https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element/8716680 – CertainPerformance Nov 09 '18 at 20:05