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

136
Visualizações
Link_to Image_tag onclick misfiring (Rails + JS)

I noticed this weird behavior when I do the following:

 <%= link_to(image_tag('some_image', class:"some_class", onclick:"someFunction(event)"),some_path) %>

later calling event.target; returns undefined. I investigated this and it is because the event is the image_tag instead of the link_to.

so I guess my question is: why does this happen and how do I prevent it?

I ended up splitting the link and the image and putting the onclick on the link_to (the image is obviously not clickable and there's this ugly button under it, just curious if there is a way around this.

Thanks in advance!

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

0

Events traverse up the dom tree, aka bubble up. target returns the element where the click happened. currentTarget returns the element where handler function is attached.

<a onclick="clickable(event)" href="#">
  <img src="/assets/sample.jpg">        <!-- if you click `img` -->
</a>

<script type="text/javascript">
  function clickable(event){
    console.log(event.target)           <!-- this will return `img` -->
    console.log(event.currentTarget)    <!-- this will return `a` -->
  }
</script>
<a onclick="clickable(event)" href="#"> <!-- if you click `a` -->
  <img src="/assets/sample.jpg">     
</a>

<script type="text/javascript">
  function clickable(event){
    console.log(event.target)           <!-- this will return `a` -->
    console.log(event.currentTarget)    <!-- this will return `a` -->
  }
</script>

If you need to get the link, make sure onclick is on the link and then call currentTarget.

about 4 years ago · Juan Pablo Isaza Relatório

0

This will add link to image and event.target will be image.

<%= link_to image_tag('some_image', class:"some_class"), some_path, onclick: "someFunction(event)" %>
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