i want to flip between two images by clicking on the image itself using javascript

Viewed 33

i want to flip between two images by clicking on the image itself. help me with the code(i want the most simplified answer, very new learner)

function changeImage(){
        var img = document.createElement('img')
            img.src =="images/pic2.jpg"
        let displayImage = document.getElementById('first')
        if (displayImage.getAttribute("src") =="images/pic.jpg") {
            
            document.getElementById('first').appendChild(img);
        }
     }
1 Answers

You can just change the src attribute of the image.

function switchImage () {
  let element = document.getElementById("myImg")
  if (element.src == "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg") {
    element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Aquilegia_vulgaris_100503c.jpg/420px-Aquilegia_vulgaris_100503c.jpg"
  } else {
    element.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg"
  }
}
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile%40original_size.jpg/367px-Chamomile%40original_size.jpg" onclick="switchImage()" />

Related