How to create a <a> link without refreshing

Asked

Viewed 751 times

0

I would like to create a link with an image, but when clicking on it does not give refresh on the page, I want that if click nothing happens, if I put # the page updates, I do not want it to happen, I want to click and nothing happens, I am using so:

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

Someone knows how to do it?
I couldn’t find anything on Google that would help.

4 answers

3

2

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

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

Already stopPropagation, 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" 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>

1


Try:

<a href="#!" class="nada"><img src="imagens/icone-construcao.png"></a>
  • This review is crazy, Gabriel Carvalho msm, putting #! the link does not point to anything, is down. You solved my problem, thank you very much!

  • @Claytonfurlanetto I think I’m wrong. #! does not solve anything, will redirect to pagina?php#! in the same way that only "#" will go to pagina?php#.

  • I don’t know if it’s the right way, but my problem solved, I tested it on the most common browsers and it worked. And pq php?

  • 1

    @hugocsl, there are several ways to solve the problem, one of them is: $(".nada"). on("click",Function(e){ e.preventDefault(); Return false; }); however, the main solution does not require knowledge in js, it is fast and solves the problem.

0

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

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

Since you’re wearing class (.nada) in the link, you can use CSS to disable the click:

.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 of pointer-events is that will disable also other mouse events, such as :hover, for example.

Browser other questions tagged

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