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 (<a>
) on my page that trigger the jquery click() handler, which will load a new page into a div without reload. To make those links available to non-javascript users, I want to link them to the same page (that's why I'm using s and not just any div/span/button). Propblem with that is that the script will reload anyway, so you can say jaavascript is overwritten.
So how do I prevent the browser using the link as a link with javascript? Or what's the correct solution to allow non-javascript users to be able to use the site properly as well ?
The only solution I could come up with by myself is just using buttons, but I find that quite bulky as I have to use a form although I only submit 1 variable via GET
which is only specified in the link itself. Thanks for help :)
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...Then, if javascript is disabled, it will follow the
<a>
tag to the newhref
as expected.jQuery gives you several ways to deal with this problem.
Hope that helps.
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:
The click will be cancelled but the css ALSO won't execute.
Using .preventDefault() is pretty standard and won't cause this issue.
For what you're doing, returning
false
will work as others have answered, but beware of overusingreturn 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:
Since you say you're using jQuery, return
false
in the event handler.