How to make a link trigger a javascript function without redirection? [duplicate]

1

I was trying to make clicking a Link HTML <a></a> run a javascript function, I a priori had the following idea to link a onclick attribute to the <a> tag like this:

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

But this way, when the page is clicked back to the top of the scroll,

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

    
asked by anonymous 03.11.2015 / 16:35

2 answers

3

As the question does not have a jQuery tag, then 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="http://pt.stackoverflow.com/">Stackoverflow em Portugues</a>  

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

event.preventDefault();
    
03.11.2015 / 17:02
2

You can basically use two forms:

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

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

OR

Add a id to the link

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

and use a listener linked to id

  

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

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