skip to Main Content

Firstly sorry if this seem a dumb question but I am learning javascript so may have messed this up.

I have an image that clickis replaced by nother image in its place.The problem I am trying to worj out is where do i place the second image link.

HTML below

 <div class="col-lg-3">

<img id="pbook" onclick="imageChange" class="imagebooks"  src="images/pink1.jpg" alt="">


 </div>

Javascript incomplete below:

function imageChange (newImage) {

 var secondImage= document.getElementById("pbook");
  secondImage.style.src = newImage;


}

Thank you for your kind help.

I have tried to create a function that when the image is click by the user is switches to another image. Basically the front image of a book that is then clicked on shows thw bck of the book.

2

Answers


  1. You almost got it right. You need to store the in-active image source somewhere:

    <div class="col-lg-3">
        <img id="pbook" class="imagebooks" src="images/pink1.jpg" data-src="images/pink2.jpg">
    </div>
    

    You’ll be able to access the data-src through dataset in javascript, and thus, simultaneously store the in-active image.

    const image = document.getElementById("pbook");
    
    image.onclick = () => {
        const newImage = image.dataset.src;
    
        image.dataset.src = image.src;
        image.src = newImage;
    }
    
    Login or Signup to reply.
  2. You can pass the second image link (images/pink2.jpg) to the function like the following way:

    <div class="col-lg-3">
      <img id="pbook" onclick="imageChange('images/pink2.jpg')" class="imagebooks" src="images/pink1.jpg" alt="">
    </div>
    
    <script>
      function imageChange(newImage) {
        var secondImage = document.getElementById("pbook");
        secondImage.src = newImage;
       }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search