How to make a Link trigger a javascript function without redirection?

Asked

Viewed 1,388 times

1

I was trying to get that by clicking on a Link HTML <a></a> a javascript function is executed, I had a priori the following idea to attach an attribute onclick on the tag <a> in this way:

<a href="#" onclick="funcao()">OnClick</a>  

However this way there is when being clicked the page back to the top of the scroll.

Question: How to trigger a javascript function without having this scroll (without any effect, transparent to the user)?

  • 1

    <a href="javascript:void(0)" onclick="funcao()">OnClick</a>, I can’t remember now, but this way it doesn’t work?

  • @Guilhermelautert I have not tested in this way :-(

  • @Sanction, did not know the Pointer-Events, it was worth the day.

2 answers

3


As the question does not have a jQuery tag, so I decided to add this answer in contrast to Ricardo’s.

var meuLink = document.getElementById("meuLink");
meuLink.addEventListener("click", function(event) {
   event.preventDefault();
});
<a id="meuLink" href="/">Stackoverflow em Portugues</a>  

So to cancel the redirect, you just need to add the following line in the method body:

event.preventDefault();
  • Good answer, I didn’t add jquery by license, but I already did, in my answer I used jquery and only javascritp, (I did and answered my question :-) ). +10

  • @Ricardo, I don’t particularly use Javascript inline (problems with readability, accessibility, page size, lack of cache, and maintainability), so I wouldn’t href="javascript:funcao()" or onclick="funcao", another point of return false; of jQuery, is that he makes use of a event.preventDefault() and of event.stopPropagation(), and in this case only the preventDefault is necessary and the stopPropagation may introduce problems.

2

You can use basically two ways:

<a href="javascript:funcao()">Href</a>  

Indicate that you want to execute a javascript function in the attribute href.

OR

Add a id to the link

<a href="#" id="executa-funcao">ID</a>

and use a Istener attached to the id

NOTE: Add a return false; so that there is no sequence in the default behavior of the link, in this case the redirect to the top of the document.

$('#executa-funcao').click(function(){
    //FAZ ALGUMA COISA
    return false;
});

Browser other questions tagged

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