How to Make an Onclick on all Page Images?

Asked

Viewed 77 times

4

I would like to know how to, when clicking on ANY image on the page, activate a function.

I tried it in the following ways: 1-

var imagez = document.getElementsByTagName('img'); 
        imagez.onclick = () =>{
      console.log(images);
    }

2-

const images = document.querySelectorAll('.janela');
//nesse caso, todas as imagens da tela teriam a classe "janela"
            images.onclick = () =>{
          console.log(images);
        }

2 answers

2


Apparently you want to install a standard event for all images on a page.

To get a list containing all page images use the method querySelectorAll() of document that will return a list of elements present in the document that match the specified selector group

document.querySelectorAll('img')

The object returned by document.querySelectorAll() is a NodeList and despite NodeList not to be a Array, can be iterated using the method foreach().

To register an event use the method addEventListener() for each image element.

//Assim que a página estiver carregada.
window.addEventListener("load", () => {

  //Para cada imagem da página.
  document.querySelectorAll('img').forEach((item) => {
   
    //Registra o evento click.
    item.addEventListener('click', (e) => {
      console.log(e.target);
    });

  });

});
<!DOCTYPE html>
<html>

<body>

  <h2>HTML Image</h2>
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf" alt="Trulli" width="100" height="66">
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/talent/logo-sotalent.svg?v=7b55c953cfdf" alt="Trulli" width="100" height="66">
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/sf/sf-logo.svg?v=5cfc8f44c8a3" alt="Trulli" width="100" height="66">

</body>

</html>

2

You got off to a great start by capturing all the images and placing them inside a variable. He just forgot that your variable "image" has now become a "array".

In this case you could have used the Repeat structure "for": take the example:

let imagez=document.getElementsByTagName('img')

for(let i=0;i<imagez.length;i++){
    imagez[i].onclick=()=>{
        //colocarias aqui o comando a executar, ou chamar a função.
        //Por exemplo mostrar o número da imagem clicada
        alert(`Imagem ${i+1}`)
    }
}
<!DOCTYPE>
<html lang='pt'>
<head></head>
<body>
  <img src='imagem1.jpg' alt='Imagem 1'>
  <img src='imagem2.jpg' alt='Imagem 2'>
  <img src='imagem3.jpg' alt='Imagem 3'>
  <img src='imagem4.jpg' alt='Imagem 4'>
<body>
</html>

Browser other questions tagged

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