Skip to content Skip to sidebar Skip to footer

How To Properly Use Javascript-links For Users Without Js

I hope I'm not creating a duplicate here, but I just don't really know what to look for/didn't find anything useful yet. I got several links () on my page that trigger the

Solution 1:

If you return false to the click event handler, it will not follow through with the default action, which in your case would be to follow the link to the new page...

$('a').click(function(e) {
    // process your event...
    return false;
});

Then, if javascript is disabled, it will follow the <a> tag to the new href as expected.


Solution 2:

For what you're doing, returning false will work as others have answered, but beware of overusing return false; in jQuery event handlers.

You would probably be better served by calling preventDefault() to stop the click action only. It will prevent the link from being followed, but not stop any other handlers that may be attached. See jQuery events: stop misusing return false for a detailed explanation.

example:

$("a").click(function(event) {
    // your custom code
    event.preventDefault();
});

Solution 3:

Since you say you're using jQuery, return false in the event handler.

$("a").click(function() {
    // ...
    return false;
});

Solution 4:

jQuery gives you several ways to deal with this problem.

$('.some-link').click(function(event) {
   //just prevent browsers default behavior
   event.preventDefault();
   //stop calling all other handlers, including live
   event.stopPropagation();
   //stop calling all handlers listening to the same dom node
   event.stopImmediatePropagation()

   //do all of the above
   return false;
)}

Hope that helps.


Solution 5:

$( "a" ).click( function() {
    // ...
    return false;
});

This will prevent the event (ie the click) from changing the page but it will also prevent you from chaining methods. Method chaining looks like this:

$( "a" ).click( function(){} ).css( 'color', 'red' );

The click will be cancelled but the css ALSO won't execute.

Using .preventDefault() is pretty standard and won't cause this issue.

$( "a" ).click( function( event ) {
    // ...
    event.preventDefault();
});

Post a Comment for "How To Properly Use Javascript-links For Users Without Js"