Wednesday, March 07, 2007

Return false to prevent jumping scrollbars

I like what Harry Maugans is doing over at his site with his JavaScript how-tos. It's back-to-basics stuff, but judging from the number of Diggs he gets, people are interested in how this stuff works under the hood.

In his tutorial "How To Create A Collapsible DIV with JavaScript and CSS," Harry writes regarding the use of the HREF attribute in anchors that trigger JS actions:

Another common do-nothing insert to use for the href property is a pound sign (#), and while that will work, it'll also move the user’s scroll bar to the very top of your website, which can get quite annoying.

The way to get around the scrolling problem is to include a "return false;" in your event handler:

<a href="#" onmousedown="toggleDiv('mydiv'); return false;">
  Toggle Div Visibility
</a>

Again, basic stuff, easily overlooked.

(I wrote to Harry about this but I don't think he approved my comment. That's okay; it's why we have Trackback :)