Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery prevent anchor click

I'm trying to prevent the default anchor link and onclick event to trigger.

Here's the HTML code:

<a id="mylink" href="http://google.com" 
    onclick="window.location.href='http://google.com.au'; return false;">
Google</a>

I'm trying to prevent any redirects from occurring, using the following jQuery code:

$("#mylink").click(function(ev) {
    ev.preventDefault();
    ev.stopPropagation();
}

But it doesn't seem to work. The code still invokes the anchor onclick event and redirects to http://google.com.au

Any clues or suggestions? Thanks in advance.

like image 620
Nick Avatar asked Aug 14 '26 20:08

Nick


1 Answers

You need to clear onclick manually, as long as it is being called before .click() callback:

$("#mylink").prop('onclick', null);
like image 106
zerkms Avatar answered Aug 17 '26 09:08

zerkms