Overriding hyperlinks’ default behaviour in javascript
// July 6th, 2006 // JavaScript
No biggie, right? Write a javascript function that should do whatever is needed and just hook it up with the OnClick attribute of the hyperlink. Simple and easy.
Let’s say the function looks something like this.
<script type="text/javascript">function HandleClick() {
alert("Some message!");
}
</script>
Now let’s test it.
Click this link.
See what happened? The javascript function was executed but you still got redirected to the url set in the href attribute of the link.
This is due to the fact that we have overridden the default behaviour of the hyperlink but we still haven’t told Javascript to cancel the default behaviour.
How do we fix this? Just add return false; right after the function call, as shown below.
<a href="http://www.morethan2cents.com" onclick="HandleClick(); return false;">link</a>
By returning false, you are basically telling javascript that the link was not clicked and thus not to trigger the default behaviour.
Now try it again. Click this link.
Voila! No redirection. Alternatively, you could leave the href attribute blank (href=””). But that would basically refresh the page for obvious reasons.
No related posts.



