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

171
Views
Changing Image onclick with JavaScript

Hey i want to change a image when the img is clicked with javascript it works once if i click the picture it changes the scr but doesnt change it back

function ImgClick() {
  var img = document.getElementById("b1")
  if (img.src = "img/RoteAmpel.jpg") {
    img.src = "img/GrueneAmpel.jpg";
  } else {
    img.src = "img/RoteAmpel.jpg";
  }


}
<!DOCTYPE html>
<html>

<head>
  <title>Mouse Events</title>
  <meta charset="UTF-8">

</head>

<body>
  <h3>Mouse Events</h3>
  <img src="img/RoteAmpel.jpg" alt="Bildwechsel" title="Bildwechsel" id="b1" onclick="ImgClick()" />


</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are two problems with your code:

1. Assignment vs Comparison

You're assigning the src instead of making a comparison:

if (img.src="img/RoteAmpel.jpg") { }

should be

if (img.src === "img/RoteAmpel.jpg") { }

2. img.src might not be what you expect

When accessing img.src you'll get the full qualified URL including protocol, domain etc.

To compare the actually attribute's value use this:

img.getAttribute('src')

You can test it yourself:

function test() {
  var img = document.getElementById("b1")
      
  console.log(img.src);
  console.log(img.getAttribute('src'));
 }
    
test();
<img id="b1" src="img/RoteAmpel.jpg">

about 4 years ago · Juan Pablo Isaza 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!