Onclick event - MULTIPLE CLICKS

1119 views javascript

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 witten so far:

   function change (index) {
  var links = new Array();
  links[0] = img/videoplace.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)" >

Writting 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.

answered question

1 Answer


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
let index = 0;
const img = document.querySelector('#social');
img.addEventListener('click', () => {
  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 = (index + 1) % links.length;

posted this

Have an answer?


Please login first before posting an answer.