0

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!

1
  • 2
    As for gracefully degrading with no Javascript support, I think this article will be useful: en.wikipedia.org/wiki/… Commented Nov 1, 2009 at 17:52

2 Answers 2

4
<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).

Sign up to request clarification or add additional context in comments.

4 Comments

Alright then, I feel stupid for not just trying that first. I assumed it was more complicated :p
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.
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!
Updated in response to the clarification.
2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.