Change image in javascript after click

Asked

Viewed 1,101 times

1

How to change an image using Javascript?

I made this code here but it didn’t 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";});

1 answer

2


To begin with, here’s a functional example of what you want: Jsfiddle

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

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

Also you have two events 'on click'. By leaving the href="passo1.html" on your tag <a> you are saying that by clicking this element the user should be redirected to the link in question (by 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 it is this effect you want, change the image and open a new window then so be it.

  • In this case this target is for an iframe that comes just below the image, as I click on the image, the iframe comparison changes.. the idea is this... but I will try to do here with what you sent... I saw that in Jsfiddle it worked !!! ;)

  • Hmmm, now it makes so much more sense.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.