Onclick event in image

Asked

Viewed 8,190 times

2

Is there any way to put an onclick event in picture? I tested with a button and is working the call to function, however, I wanted to use an image.

I tried something like:

<a href="#">
   <img src="imagens/search.png" onclick="ocultaForm()">
</a>

However, it is not running the hidden functionForm(), it just redirects to #

  • Why don’t you do it like this: <a href="#" onclick="ocultaForm()"> ?

  • @hugocsl tried, but does not perform the function

5 answers

4

The onclick works perfectly on one element <img>, the problem is that your image is contained in a <a>, then when you click runs the click on link.

Following example:

function ocultaForm(){
  console.log("Oi mundo!");
}
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png" onclick="ocultaForm()">

2

    $(document).ready(function() {
        $('.thumbnails').click(function() {
            alert('teste');
           // ocultaForm(); pode chamar aqui
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />

function ocultaForm(){
    alert();
}
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onClick="ocultaForm()" />

  • 1

    Could edit your answer and explain it ? to the AP understand where the error was.

  • The problem is that your image is inside of in a link every time you click on the link it executes the link..

1


To work the way you are trying, simply remove the attribute href tag a, it is logical that the function of existing otherwise will not work!

var clicks = 1;
function ocultaForm() {
  alert('VOCÊ CLICOU NA IMAGEM!');
  if (clicks === 1) {
    console.log('Você clicou ' + clicks + ' vez na imagem!');
  } else {
    console.log('Você clicou ' + clicks + ' vezes na imagem!');
  }
  clicks++;
}
a {
  cursor: pointer;
}
img {
  width: 200px;
}
<a>
   <img src="http://www.voluntersul.com.br/editor/Image/clickaqui.png" onclick="ocultaForm()">
</a>

0

apart from the link you could do so:

<img src="imagens/search.png" onclick="ocultaForm()" style="cursor:pointer"/>
  • Does not perform the function.

0

    function teste(){
      console.log('fui clicado');
   }
  
  <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png" onclick="teste();"/>
   
    

Try it like this and see if it’s what you need.

Browser other questions tagged

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