views:

66

answers:

2

This question may have been asked before, but I had trouble finding an answer, since I didn't quite know what search terms to use.

In HTML, how do you make a link go a place, but execute JavaScript instead when it is clicked? Right now, I have a link that's somewhat like this:

<a href="#" onclick="javascript:dostuff()">Stuff</a>

But, the thing is, when someone right clicks the link, I want them to be able to copy a direct URL to the link. Also, if someone's browser does not support JavaScript, or they have it disabled, I would still like them to be able to reach the page. Is it just

<a href="http://linkhere" onclick="javascript:dostuff()">Stuff</a>?

Or is there something more complicated?

Thanks!

+3  A: 
<a href="http://linkhere" onclick="return dostuff()">Stuff</a>

Make sure that the dosuff function returns false if you want the link to not be followed when the script runs.

(The 'javascript:' is pointless. It labels a loop, but you don't have a loop. See the HTML spec for how to specify which language is being used in the intrinsic event handler attributes — better yet, use unobtrusive JavaScript and progressive enhancement).

David Dorward
Alright then, I feel stupid for not just trying that first. I assumed it was more complicated :p
AriX
OK. Thanks again.
AriX
+1 for mention of unobtrusive JavaScript.
Josh Leitzel
You may also wish to modify that to onclick="dostuff(); return false". This keeps the browser from following the link when you click on it.
Jason
No, the question was about running the JS and not following the link, sorry if I wasn't clear. I just wanted the link to appear on the status bar at the bottom of the screen and be copyable/follow-able in a new tab.Thanks Jason!
AriX
Updated in response to the clarification.
David Dorward
+1  A: 

You need to let the event return false to block the default action.

<a href="http://example.com" onclick="doSomething(); return false;">
BalusC