Change HTML/CSS/JAVASCRIPT image

Asked

Viewed 82 times

1

I am starting to learn HTML/CSS/JAVASCRIPT, and I am with a project of a site, I will try to explain what I want. I have 3 images of broken mirrors and I want to click on each image to show the photo inside the mirror, but I’m not getting it and when I click on the image it changes only a mirror.

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <title>TE AMO</title>
    <meta charset="utf-8">
      <link rel="stylesheet" type="text/css"  href="styles.css" />
     
  </head>
  <body>
<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("quadro1").src=a;
    }
</script>
</div>
      <div class="momentos-menu">
      <img src="imagens/momentos.png" class="momentos">
      <div id="quadro">
      <div class="row">
  <div class="coluna"> 
    <img id="quadro1" src="imagens/quadro.png" onclick='changeImage("imagens/quadro-foto-1.png");'>
  </div>
  <div class="coluna">
    <img id="quadro1" src="imagens/quadro.png" onclick='changeImage("imagens/quadro-foto-2.png");'>
  </div>
  <div class="coluna">
    <img id="quadro1" src="imagens/quadro.png" onclick='changeImage("imagens/quadro-foto-3.png");'>
    
  </div></div>
          </div>
      </div>
   

  </body>
</html>

1 answer

0

An id has to be unique on a page, so you’re modifying the same element. The easiest way to solve the problem is to understand that Event handlers in attributes have access to the element such as this.

function changeImage(img, src) {
  img.src = src;
}
<img src="https://picsum.photos/id/1/200" onclick="changeImage(this, 'https://picsum.photos/id/2/200')" />
<img src="https://picsum.photos/id/1/200" onclick="changeImage(this, 'https://picsum.photos/id/3/200')" />
<img src="https://picsum.photos/id/1/200" onclick="changeImage(this, 'https://picsum.photos/id/4/200')" />

But you should use addEventListener and data- Attributes and delegation of events for better separation between HTML and Javascript and also saving memory by needing an Event Handler instead of one per image.

document.getElementById("quadro").addEventListener('click', (event) => {
   const target = event.target;
   if (target.matches("img")) {
     target.src = target.dataset.over;
   }
});
<div id="quadro">
  <img src="https://picsum.photos/id/1/200" data-over="https://picsum.photos/id/2/200">
  <img src="https://picsum.photos/id/1/200" data-over="https://picsum.photos/id/3/200">
  <img src="https://picsum.photos/id/1/200" data-over="https://picsum.photos/id/3/200">
</div>

  • Thank you first for the answer and help, but when trying to use the first code I did not succeed and simply by clicking on any frame the first disappeared, and in the second code appeared no visible effect.

  • @Rianbittencourt I don’t know what you didn’t get, but I created an example that you can run right here

Browser other questions tagged

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