Home > Software engineering >  i want to flip between two images by clicking on the image itself using javascript
i want to flip between two images by clicking on the image itself using javascript

Time:08-25

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);
        }
     }

CodePudding user response:

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@original_size.jpg/367px-Chamomile@original_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@original_size.jpg/367px-Chamomile@original_size.jpg"
  }
}
<img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Chamomile@original_size.jpg/367px-Chamomile@original_size.jpg" onclick="switchImage()" />

CodePudding user response:

the easiest way is to load the 2 images and leave the display on only one at a time

sample code

const flipper = document.querySelector('#flip-2-images')

flipper.onclick = e =>
  {
  let isOne = flipper.classList.toggle('one') 
  flipper.classList.toggle('two', !isOne )
  }
#flip-2-images
  { 
  cursor : pointer; 
  }
#flip-2-images.one > img:nth-child(2),
#flip-2-images.two > img:nth-child(1) 
  { 
  display : none; 
  }
<div id="flip-2-images" >
  <img src="https://picsum.photos/200/300?random=1">
  <img src="https://picsum.photos/200/300?random=2">
</div>

  • Related