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?

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.

+1, but a lot of people will put href="#" in the links they plan on using with javascript.
–
GromerMay 15 '09 at 1:01

okay, I'm an idiot. I thought that was the thing to do but it wasn't working. turns out it was just IE caching the javascript so it wasn't executing my new line with return false.
–
Max SchmelingMay 15 '09 at 1:03

@Gromer - The idea is to make it work with or without javascript.
–
Max SchmelingMay 15 '09 at 1:03

4

href="#" does scroll the page back up to the top ...
–
QuentinMay 15 '09 at 6:41

1

No as my code is, David. Only if you neglect to return false;
–
Paolo BergantinoJul 10 '09 at 18:12

Returning false does work for IE, but not for Firefox or Chrome; This solution did work for both, Thanks!
–
DerrickAug 26 '11 at 14:00

Two additions: 1) One may want to call preventDefault() before doing something cool. 2) Add this in the beginning of the function to support middle mouse button correctly: if(event.which != 1) return;
–
Mikhail OrlovOct 1 '14 at 12:52

Well I am working with jQuery (like the majority of people on this site it seems), even though I didn't specify... but thank you for the post, it may be useful to somebody.
–
Max SchmelingMay 15 '09 at 14:09

ok, i see. I think frameworks may be useful to big powerful projects. But for small sites...
–
Sergei KovalenkoMay 17 '09 at 17:25

4

Javascript frameworks are useful on all size sites that care about browser compatibility. Plus, using inline events is a bad practice overall.
–
Paolo BergantinoJul 10 '09 at 18:14

there are no needed frameworks at 4px.ru (: Using inline event isn't bad for one element. And for many similar elements with similar actions we can set event handlers by script.
–
Sergei KovalenkoJul 12 '09 at 9:08