How To Properly Use Javascript-links For Users Without Js
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...returnfalse;
});
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() {
// ...returnfalse;
});
Solution 4:
jQuery gives you several ways to deal with this problem.
$('.some-link').click(function(event) {
//just prevent browsers default behaviorevent.preventDefault();
//stop calling all other handlers, including liveevent.stopPropagation();
//stop calling all handlers listening to the same dom nodeevent.stopImmediatePropagation()
//do all of the abovereturnfalse;
)}
Hope that helps.
Solution 5:
$( "a" ).click( function() {
// ...returnfalse;
});
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"