Search code examples
javascriptcssdom-eventsanchor

Styling anchor tags without href's--being used to trigger Javascript within page


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?


Solution

  • 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!