Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
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. 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);
        }
     }
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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()" />

about 4 years ago · Santiago Trujillo Report

0

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" class="one">
  <img src="https://picsum.photos/200/300?random=1">
  <img src="https://picsum.photos/200/300?random=2">
</div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!