How to change only one image with Javascript

I have an image with two small image/buttons on top of it. Each image/button should change the main image to either the original image or to the alternative image. I have a small javascript function to make it work. But the problem comes when I want to have 2+ images with the same functionality on the same page. The button changes all images at once. Is there a simple solution so that the JS only changes the image within the DIV in which the button is pressed?

HTML:

    <div class="mobile-product-image-switcher">
      <img src="main-image.jpg" alt="" class="mobile-product-switcher-image" />
      <img src="switcher-button-1.jpg" alt="" class="switcher-button-1" onclick="changeImg('main-image.jpg')" />
      <img src="switcher-button-2.jpg" alt="" class="switcher-button-2" onclick="changeImg('main-image-2.jpg')" />
    </div>

<div class="mobile-product-image-switcher">
      <img src="main-image-3.jpg" alt="" class="mobile-product-switcher-image" />
      <img src="switcher-button-1.jpg" alt="" class="switcher-button-1" onclick="changeImg('main-image-3.jpg')" />
      <img src="switcher-button-2.jpg" alt="" class="switcher-button-2" onclick="changeImg('main-image-4.jpg')" />
    </div>

CSS:

.mobile-product-image-switcher {
  position: relative;   
  top: 0;
  left: 0;
  width: 200px;
  height: 200px;
  z-index: 1;
}

.mobile-product-switcher-image {
  position: relative;
  top: 0;
  left: 0;
}

.switcher-button-1 {
  position: absolute;
  bottom: 10px;
  right: 50px;
  width: 30px;
  height: 30px;
  z-index: 2;
  background-color: white;
  border-radius: 30px;
  padding: 5px;
  cursor: pointer;
}

.switcher-button-2 {
  position: absolute;
  bottom: 10px;
  right: 15px;
  width: 30px;
  height: 30px;
  z-index: 2;
  background-color: white;
  border-radius: 30px;
  padding: 5px;
  cursor: pointer;
}

JS:

function changeImg(src){
    $('.mobile-product-image-switcher img.mobile-product-switcher-image').attr('src', src);}

Thank you

48 thoughts on “How to change only one image with Javascript”

  1. What i don’t understood is in reality how
    you’re no longer actually a lot more smartly-appreciated than you may be now.

    You’re very intelligent. You recognize therefore significantly in relation to
    this subject, produced me personally believe it from numerous
    numerous angles. Its like men and women aren’t interested unless it is
    one thing to do with Lady gaga! Your personal
    stuffs excellent. At all times handle it up! http://antiibioticsland.com/Ampicillin.htm

    Reply

Leave a Comment