Swap image by clicking it (JS, jquery)

Asked

Viewed 863 times

2

I want to click on an image, and when I click on it, it will pull an api and I want the image to change to another one, only I can’t change the image.

Note: the API is working, I just need to know how to change the photo when I click on it.

  • Hi Nazare, you can show the code you have?

2 answers

1


Having the URL of the new image, you just need to select the element <img> to be changed and to change the attribute src from it. In the example below I chose two Urls and used pure Javascript to rotate between them every click on the link or image using addEventListener:

function mudaImagem () {
  var imgA = 'https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg';
  var imgB = 'https://i.pinimg.com/736x/ae/d7/bc/aed7bcbe347a262f89cc3867cdce54c2--cutest-kittens-ever-cute-baby-animals.jpg';
  var img = document.querySelector('img');
  img.src = (img.src == imgA ? imgB : imgA);
}

document.querySelector('a').addEventListener('click', mudaImagem, true);
document.querySelector('img').addEventListener('click', mudaImagem, true);
img {
  border: 10px solid white;
  outline: 1px solid black;
  width: 150px;
  height: 150px;
}
<a href="#">Mudar imagem</a>
<br>
<img src="https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg">

0

Complementing the above Answer, the ideal would be instead of using Document.querySelector to use Document.getElementById as the selector because there are definitely more than 1 image and more than 1 link in your application, since getElementById selects through an id that must be unique so it is possible to ensure the operation.

Follow the example of nunks.lol altered as I explained.

JAVASCRIPT

<script>
  function mudaImagem () {
    var imgA = 'https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg';
    var imgB = 'https://i.pinimg.com/736x/ae/d7/bc/aed7bcbe347a262f89cc3867cdce54c2--cutest-kittens-ever-cute-baby-animals.jpg';
    var img = document.getElementById('clickImagem');
    img.src = (img.src == imgA ? imgB : imgA);
  }

  document.getElementById('clickLink').addEventListener('click', mudaImagem, true);
  document.getElementById('clickImagem').addEventListener('click', mudaImagem, true);
</script>

CSS

img {
  border: 10px solid white;
  outline: 1px solid black;
  width: 150px;
  height: 150px;
}

HTML

<a id="clickLink" href="#">Mudar imagem</a>
<br>
<img id="clickImagem" src="https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg">
  • Douglas, what if when I clicked on another link intending the previous one to return to the normal image it was before being clicked, as it would be???

Browser other questions tagged

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