How to cancel navigation when user clicks a link (<a> element)?

Viewed 81733

I'm trying to load some stuff using AJAX when a user clicks a link, but I want the link to actually go somewhere so that the app still works when javascript is disabled. Is there any way to just do something with javascript and cancel navigation when a link is clicked?

What's the best practice? Can that be done, or do I need to replace the link using javascript or what?

10 Answers

If you have HTML like this:

<a href="no_javascript.html" id="mylink">Do Something</a>

You would do something like this with jQuery:

$(document).ready(function() {
    $('#mylink').click(function() {
        doSomethingCool();
        return false; // cancel the event
    });
});

All you have to do is cancel the click event with Javascript to prevent the default action from happening. So when someone clicks the link with Javascript enabled, doSomethingCool(); is called and the click event is cancelled (thus the return false;) and prevents the browser from going to the page specified. If they have Javascript disabled, however, it would take them to no_javascript.html directly.

why jQuery?

HTML:

<a href="no_javascript.html" onclick="return doSmth()">Link</a>

...and javascript code:

function doSmth(){
  // your code here
  return false
}

for IE at least, just put this.event.returnValue = false; at the end of the method.

e.g:

function onClickFunction()
 {
  someMethod();
  this.event.returnValue = false;
 }

I had a complex method where this did the trick.

I use document.location.replace to navigate, but when I want to cancel the navigation, return false (in the same function as document.location.replace) doesn't cancel the navigation.

I just used

<a href="https://ryanhigdon.com" onClick={ event => {
  event.preventDefault()
}}>Take me away</a>

In my use case I wanted to perform some actions before navigation.

is simple, use rel="nofollow" attribute

 <a href="signin.php" rel="nofollow">sign in</a>
Related