If you play with our post GenX – first public demonstration, you’ll see that the an internal link marker “
“. Clicking on any of these links will bring you a highlighted section of the document, such as this. You’ll also see this on Wikipedia, for example here.
The way to do this is quite simple with CSS3 using the ‘:target’ pseudo-class:
div.gencard:target {
background-color: rgb(228, 241, 228);
}
But let’s say you don’t have access to CSS3 or you need to highlight a parent element (this is actually how I started this investigation). CSS doesn’t provide a way to select a parent element that has a child with a certain set of properties.
Given that we can’t use CSS, the next tool we look to is JS. One’s initial take for this would be quite simple:
- create a document load event
- in that event, look at window.location.hash
- if substr(1) refers to an existing element, highlight whatever it is you need
But what happens if you click on an “internal link”, e.g. one like <a href=”#id_internal”>? Well, after a little research it turns out you’re out of luck – no DOM provides such an event. Alas, it turns out – as far as I’ve been able to see – the solution is write a little JS timer than monitors the window.location for changes, and if it has, update your highlight appropriately.
Further reading:
- http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2007-August/012330.html
- Gecko DOM Reference
- Bookmarking in AJAX apps (vaguely related, some useful JS)
I’m not sure if the target pseudo-class discriminates what page, or even what domain, a link refers to. I think any link with a fragment identifier would trigger that pseudo-class (though I haven’t tested this).
Also, I’m pretty sure most sites tend to use those link markers for external links, rather than internal document fragments.
One method of identifying external links (with obvious drawbacks) is to test for a protocol at the beginning of the href attribute (in CSS3):
a[href^=http\:\/\/] {
background: transparent url(images/ext.link.png) right center no-repeat;
padding-right: 16px;
}
It’s safe in that it fails gracefully, though I’m sure a better solution must exist…
Loving the blog David!