HTML Anchors and Hyperlinks Link that runs JavaScript


Example

Simply use the javascript: protocol to run the text as JavaScript instead of opening it as a normal link:

<a href="javascript:myFunction();">Run Code</a>

You can also achieve the same thing using the onclick attribute:

<a href="#" onclick="myFunction(); return false;">Run Code</a>

The return false; is necessary to prevent your page from scrolling to the top when the link to # is clicked. Make sure to include all code you'd like to run before it, as returning will stop execution of further code.

Also noteworthy, you can include an exclamation mark ! after the hashtag in order to prevent the page from scrolling to the top. This works because any invalid slug will cause the link to not scroll anywhere on the page, because it couldn't locate the element it references (an element with id="!"). You could also just use any invalid slug (such as #scrollsNowhere) to achieve the same effect. In this case, return false; is not required:

<a href="#!" onclick="myFunction();">Run Code</a>

Should you be using any of this?

The answer is almost certainly no. Running JavaScript inline with the element like this is fairly bad practice. Consider using pure JavaScript solutions that look for the element in the page and bind a function to it instead. Listening for an event

Also consider whether this element is really a button instead of a link. If so, you should use <button>.