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

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?


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.


None of this worked for me with the Google Chrome browser.

Here's what did work though (using jQuery):

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

why jQuery?

HTML:

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

...and javascript code:

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

What I would do are :

a. for href attribute, javascript:void(); will be set

b. for onclick event, will provide a function to handle the click event and that function will return false.

eg:

<script type="text/javascript">
   function myfunction()
   {
      //do something
      return false;
   }
   </script>

   <a href="javascript:void();" onclick="myfunction()">Link</a>

<a href="http://www.google.com" class="ignore-click">Test</a>

with jQuery:

<script>
    $(".ignore-click").click(function(){
        return false;
    })
</script>

with JavaScript

<script>
        for (var i = 0; i < document.getElementsByClassName("ignore-click").length; i++) {
            document.getElementsByClassName("ignore-click")[i].addEventListener('click', function (event) {
                event.preventDefault();
                return false;
            });
        }
</script>

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored