views:

330

answers:

2

What is the most cross-browser effective way to style anchor tags without href's?

I found this article on making the styles apply in older versions of IE by throwing in an href="#". However, I am applying this about halfway down the page and find that it acts as it should; brings you to the top of the page again. This makes the page 'jump' which is a bad experience for anyone trying to use the bottom half of the page. But...when I take the href's out IE will not apply the css styles.

Thoughts?

A: 

Use href="javascript:void(0)" in place of #. This is the most common method to get around this problem.

The anchor still gets an href attribute, but it doesn't do anything.

zombat
Not good for accessiblity because people with Javascript enabled will still see clickable links, but they do nothing. That's not very nice!
Josh Stodola
It's better than having a clickable link with the '#' that just scrolls you to the bottom of the document.
zombat
+1  A: 

Use markup like this...

<a id="myLink" href="JavascriptDisabled.htm">Jump</a>

JavascriptDisabled.htm should be a page that says Javascript must be enabled for this to work!

Then you can override the default click functionality of the link with unobtrusive Javascript like this...

window.onload = function() {
  document.getElementById("myLink").onclick = function() {
    //Execute your Javascript
    return false; // This prevents the redirect
  }
}

So people with Javascript enabled get the correct functionality. Those with Javascript disabled will actually get a message that tells them why it's not working. I'd say it's a win/win!

Josh Stodola
I've always used window.onload in the body tag, but over herehttp://javascript.about.com/library/blonload.htmit talks about separating the javascript out more into the js file. I suppose that creates cleaner code...
velvetpuzzle
Yes it is called behavioral separation, and it is the thing to do these days. It's much easier to maintain.
Josh Stodola