JavaScript Ignore HREF Attribute Value

By Akbar

On the web programming, it’s common to use the “#” as the HREF value and apply the event handler on the “click” event. But if you don’t return false in the “on click” event handler, the “#” will be appended to the URL when user click on that link and it may ugly and even worse break some functionality. A common recommend way to do this is something like:

<a href="#" onclick="dosomething();return false;">Click Me</a>

This works well when you are adding the onclick event handler directly as part of the HTML, but fails when you need to bind the “click” event using the Even Listener model (as in this case multiple event handler could be bound with a single event). Here is an equivalent workaround for this which works in case of multiple event handlers too:

<a href="javascript:" onclick="dosomething();return false;">Click  Me</a>

As you can see we have replaced the “#” with “javascript:” which means just don’t perform any JavaScript operation. Neat and Simple.

Tags: , ,