Stupid anchor tag hack

Dave Cortright
on June 22, 2008 8:00 PM | | Comments (1)
a-href-hack.png
So I am by no means an HTML/CSS expert. In fact I'm more of a hack. But that's what agile development is all about: getting something that works sufficiently well now with minimal time invested. And that's what this hack is all about.

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!

1 Comments

This isn't great from an accessibility perspective but a nice tip nonetheless!

Leave a comment