Change image by clicking on it (JS, jQUERY)

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, but I can not change the image.

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

    
asked by anonymous 13.10.2017 / 18:58

2 answers

1

Having the URL of the new image, you just need to select the <img> element to be changed and change the src attribute of it. In the example below I chose two URLs and used pure JavaScript to rotate between them with each 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">
    
13.10.2017 / 19:34
0

Complementing the above answer, the ideal would be instead of using document.querySelector to use document.getElementById as selector because there are certainly 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 guarantee the operation.

Follow the modified nunks.lol example as 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">
    
14.10.2017 / 16:48