Change image in javascript after click

1

How do I change an image using JavaScript?

I made this code here but it did not work.

HTML file

  <a href="passo1.html" target="janela">
     <img id="passo1" class="passo" src="img/passo_color1.png" style="float:left">
  </a>

JS file

            teste = document.querySelector("#passo1").addEventListener('click', function(){
teste.src = "img/passo_color.jpg";});
    
asked by anonymous 08.08.2015 / 05:34

1 answer

2

Here's a working example of what you want:

Note that to reference the element itself you should use 'this':

document.querySelector("#passo1").addEventListener('click', function(){
    this.src = "img/passo_color.jpg";
});

Additionally you have two 'on click' events. When you leave href="passo1.html" in your <a> tag you are saying that when you click on this element the user must be redirected to the link in question (when leaving target="window" at least it will open another window and not redirect the window itself to another link).

In my example I left without, but if this effect even if you want, change the image and open a new window so be it.

    
08.08.2015 / 07:25