href all the things

Allowing href on any element was an interesting proposal but has so far been gathering dust in favour of “block-level” links—allowing an anchor element to be the parent of a block-level element—but what if that was a mistake?

This is no new subject, just something I’ve been thinking about recently that should not be taken at all seriously.

See my href all the things demo

Firstly, anchors around block-level elements just feel dirty; you’re wrapping an extra element around a thing that gives the effect that said thing is doing the thing you want it to. Can’t the thing do that stuff itself?!

CSS3 Attribute Selectors offer a new, cleaner method for both coding and styling “href anywhere”:

// href all the things
// Click on any element with an href attribute
// to navigate to its value

$('[href]').click(function(e) {

    // Navigate to the element's href value
    location.href = $(this).attr('href');

    // Prevent bubbling, so both child and parent
    // can have different hrefs
    return false;

});

Use-cases

  • Table row is a link
  • Main <h1> can itself be the link to the homepage
  • List Items can be navigational links in menus

Useful styes

Since a:link and its brethren no longer apply, you’ll need something like the following:

[href] {
    color: blue;
    text-decoration: underline;
}

[href]:hover {
    color: green;
    cursor: pointer;
}

[href]:active {
    color: red;
}

Advantages

  • Allows any element to trigger a URL change
  • Doesn’t require the addition of an extra element as in the case of block-level links

Disadvantages

  • It won’t work if JavaScript isn’t available
  • Won’t show the href value in the browser’s status bar (and isn’t possible to simulate since window.status was disabled in most browsers—even IE7!)
    • A title attribute could be used as a visual accessibility cue by setting its value being the href value
  • Cannot style visited links (:visited won’t work and browser security prevents you checking if the href value is in its history)
    • You could do something nasty and black-hat like add a link to the DOM and see if its colour is purple, but don’t.
  • Middle-click opens location in current tab/window
  • Right-click menu doesn’t show options for links

Conclusion

href anywhere might be viable for web apps but accessibility disadvantages mean it’s probably just not worth it for sites. While the extra element required for block-level links isn’t ideal, it’s the lesser of two evils in this case.

Sorry, Eric.

References

Leave a Reply

Your email address will not be published.