Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda