How to create a link to without giving refresh

0

I would like to create a link with an image, but when clicking it does not refresh the page, I want to click if nothing happens, if I put the page refreshes, I do not want this to happen, I want it to click and nothing I'm using it like this:

<a href="#" class="nada"><img src="imagens/icone-construcao.png"></a>

Does anyone know how to do this?
I did not find anything on Google that would help.

    
asked by anonymous 25.02.2018 / 18:43

4 answers

1

Try it out:

<a href="#!" class="nada"><img src="imagens/icone-construcao.png"></a>
    
25.02.2018 / 19:07
4

Another option:

<a href="javascript:void(0)" class="nada">
  <img width="200" src="https://s7d2.scene7.com/is/image/PetSmart/PB1201_STORY_CARO-Authority-HealthyOutside-DOG-20160818?$PB1201$"></a>

Moreabout: link

    
25.02.2018 / 19:14
2

Use the method preventDefault or stopPropagation . It serves to cancel an action determination.

The difference between the two is that preventDefault will only cancel the event "from that" element that "suffered" the action.

Already stopPropagation , will cancel the event of all child elements.

Example:

document.querySelector("#google").addEventListener("click", ev => {
  ev.preventDefault();
  alert("Você não será redirecionado.")
});

document.querySelector("#sites").addEventListener("click", ev => {
  ev.preventDefault();
  alert("Você não será redirecionado.")
});
<a href="https://www.google.com.br" id="google">Google</a><br>
<a href="https://www.instagram.com" id="intagram">Instagram</a><br>

<div id="sites">
    <a href="https://fb.com">Facebook</a><br>
    <a href="https://twitter.com">Twitter</a>
</div>

Or you can also remove href and add a cursor via CSS.

a {
  cursor: pointer;
}
<a class="nada"><img src="http://via.placeholder.com/350x150"></a>
    
25.02.2018 / 19:10
0

One way is to use event.preventdefault() na in the onclick attribute:

<a href="#" onclick="event.preventDefault();" class="nada">
    <img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg"></a>

Sinceyouareusingclass(.nada)inthelink,youcanuseCSStodisabletheclick:

.nada{pointer-events:none;}

Example:

.nada {
  pointer-events: none;
}
<a href="#" class="nada">
   <img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg">
</a>
  

The problem with pointer-events is that it will also disable others   mouse events such as :hover , for example.

    
25.02.2018 / 20:21