Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
HTML image object on click is not working

I am trying to build a gallery that opens up a large popup image or 'modal' image when a picture is clicked.

I am trying to combine the code from these two tutorials:

https://www.w3schools.com/howto/howto_js_portfolio_filter.asp https://www.w3schools.com/howto/howto_css_modal_images.asp

Hovering over the image causes it to fade a little but clicking does absolutely nothing.

Here is a chunk of my code.

HTML:

<div class="column 1">
<div class="content">
  <img id ="myImg" src="path.png" alt="img" style="width:40%">
  <div id="myModal" class="modal">
    <span class="close">&times;</span>
    <img class="modal-content" id="img01">
    <div id="caption"></div>
  </div>
</div>

JS:

var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick() = function(){
  console.log('click')
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

Nothing is being outputted to the console, not even any error messages.

Any help is much appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Remove the () from the onClick method, so your JavaScript looks like:

var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  console.log('click')
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

onClick is an attribute of a DOM element, not a function. As such, you need to assign the anonymous function to the variable with the variable assignment syntax.

See https://jsfiddle.net/7yxf3uvp/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda