I have no special talent. I'm only passionately curious - Albert Einstein
April 17, 2009
javascript functions in anchor tags: RETURN FALSE!!!
Posted by Dave Malone
in Javascript,
Best Practices,
Technology
This is more of a rant than anything. Have you ever been on a website, scrolled down to the middle of the page, and found a little slideshow control or some other anchor tag which is really controlled via the onclick method? Have you ever clicked it, and seen that you're now located at the top of the page again? How annoying is that!
As a developer, it's the most annoying thing to think that someone has developed a poor user experience. As an example, check out the latest Samsung LED tv. Under the Series 7 sub-tab, there are navigational arrows (<, >) which will show you more information about the TV. Scroll down the page, click on one of those arrows, and you'll see what I'm talking about. The simple solution: to prevent bubbling on the page, make sure the called javascript function returns false at the end of the statement. Here's an example:
<script type='text/javascript'>
function goodFunc(){
alert('I will not ruin your experience');
return false;
}
function badFunc(){
alert('I have ruined your experience');
}
</script>
<body>
<p>
...lots of content
</p>
<a href="#" onclick="return goodFunc()">I'm good</a>
<br />
<a href="#" onclick="return badFunc()">I'll make your Monday worse</a>
</body>