Link that runs JavaScript

suggest change

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.

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

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents