Alternative for Hyperlink using # for HREF (a href=#) Scrolling Issue with Javascript OnClick

When hooking up javascript events on your hyperlink anchor tags, many developers will set the HREF property to "#". If you don't do something like that, then when you click on your link, it will navigate your page to an invalid URL which is not what you want. For instance, if you were to do something like this:

<script type="text/javascript">
    function doSomething() {
        // do some javascript action here...
    }
</script>
 
<a href="" onclick="doSomething();">Test Link</a>

 
This example will usually just navigate your page to the root URL of your web domain directory which is not what you intended.



Normally, you will see the "#" as the HREF parameter instead. This is great because it will run your javascript and not navigate away from the page. Here's what the example looks like with HREF="#":

<script type="text/javascript">
    function doSomething() {
        // do some javascript action here...
    }
</script>
 
<a href="#" onclick="doSomething();">Test Link</a>

 
There is are a couple of BIG draw backs to this approach. Especially in IE, you will hear a noticable "clicking" sound when the link is clicked. What's even worse, if the page is scrolled down at all, it will cause the page to re-scroll back to the top of page whenever the link is clicked which is really annoying. On top of that, it will add a "#" sign to the end of your current URL which is ugly and pointless.

Many javascript developers use this syntax:

<script type="text/javascript">
    function doSomething() {
        // do some javascript action here...
    }
</script>
 
<a href="javascript:void(0);" onclick="doSomething(); return false;">Test Link</a>

 
This approach works on most modern browsers but is NOT recommended. Many older browsers and even some new ones like Opera, do not like this syntax and try to actually navigate to this URL.

The Best Approach
The best approach I've found is to cancel the navigation whenever your link is clicked by adding a "return false;" to the end of your onclick event and navigating to "#" like this:

<script type="text/javascript">
    function doSomething() {
        // do some javascript action here...
    }
</script>
 
<a href="#" onclick="doSomething(); return false;">Test Link</a>

 
Now when you click the link, your javascript will execute but no clicking sound will be played and your scroll position is not altered.