Event onclick in image

2

Is there any way to put an onclick event into image? I tried with a button and the call to the function is working, but 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 only redirects to #

    
asked by anonymous 02.02.2018 / 13:17

5 answers

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><imgsrc="../images/bottle.jpg" alt="bottle" class="thumbnails" />

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

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

Here's an example:

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

By taking the link you could do this:

<img src="imagens/search.png" onclick="ocultaForm()" style="cursor:pointer"/>
    
02.02.2018 / 13:24
0

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

Try this and see if that's what you need.

    
02.02.2018 / 15:46
0

To work out the way you're trying, just remove the href attribute from the a tag, and of course the function to exist 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>
    
02.02.2018 / 16:44