Simply use the
You can also achieve the same thing using the
<a href="#" onclick="myFunction(); return false;">Run Code</a>
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?
Also consider whether this element is really a button instead of a link. If so, you should use