I often want to display a link on a web page, but I want to execute some Javascript when the link is clicked rather than navigating to a new page. Browsers don't like it if an <a> anchor link doesn't have something in the href property; they show their displeasure by ignoring the <a> tag altogether and rendering the contents as plain text.
I started off using "#" as the href value, since that keeps the browser on the same page. However, # is a reference to the top of the page, so if the user has scrolled down at all, it will scroll the page back up to the top.
So I started using "#/" as the href. Since there is no anchor on my pages defined as "/", this won't change the scroll position of the page. And since the href value gets added to the end of the URL, the #/ doesn't look too much out of place. Here is an example.
If anyone has suggestions on how to get the anchor to show up as a link, execute a javascript, not change the page or scroll position, and not change the URL in the address bar, I'd love to hear it. Leave a comment!
This isn't great from an accessibility perspective but a nice tip nonetheless!
Posted by: Arthur Klepchukov | June 23, 2008 at 12:52 AM
This is kind of old, so I'm not sure if you've figured it out, but it's really not that hard.
When setting the javascript event to the link (whatever href) just end it with return false;.
This just means the link won't go to the actual href, meaning it won't scroll anywhere and won't change the url in the address bar.
Posted by: Chris | March 17, 2009 at 03:51 PM
Thanks, Chris. Yeah I figured that trick out after this post. Of course for those browsers that don't support JavaScript or have it turned off, it's good to have a fall back. I've taken to doing both.
Posted by: Dave Cortright | March 17, 2009 at 08:15 PM
I have found that you can simply leave out the href part completely. at least with IE7 and Firefox3. I haven't tested on older browsers.
example:
text
Anybody know if this is a problem and I'm just not seeing it?
Posted by: Michael | April 09, 2009 at 09:46 AM
just make it
href="javascript:myfunction(myargs)"
and you won't even need the onClick property ;)
Posted by: gaps | May 09, 2010 at 03:12 PM