Primary image for Highlighting Named Anchors with jQuery

Highlighting Named Anchors with jQuery

I’ve always disliked the way named anchors (<a href="#name">...</a>) behave in browsers. It jumps your viewport to a different part of the page, but it’s rarely obvious which section you have landed on. If the page is long enough, the referenced section will start at the top of your browser, but where does it end? If the content is towards the bottom of the page, it may not be at the top of the page, but somewhere in the middle. And what if your content is in two columns? Or a table? What you’ve linked to becomes totally ambiguous.

Sphinx uses named anchors quite a bit, so I wanted something that would improve their usability for Django Best Practices. That’s when I dug up this clever little jQuery snippet from our code vault.

// highlight and fade background on named anchors
// requires jquery.color.js http://plugins.jquery.com/project/color
function highlight(elemId){
var elem = $(elemId);
elem.css("backgroundColor", "#ffffff"); // hack for Safari
elem.animate({ backgroundColor: '#ffffaa' }, 1500);
setTimeout(function(){$(elemId).animate({ backgroundColor: "#ffffff" }, 3000)},1000);
}

if (document.location.hash) {
highlight(document.location.hash);
}
$('a[href*=#]').click(function(){
var elemId = '#' + $(this).attr('href').split('#')[1];
highlight(elemId);
});
This will briefly highlight and fade the <span class="caps">DOM</span> element referred to by the named anchor (technically, we&#8217;re using the id attribute, not the name attribute). You can see it in action by clicking here.

The link above should highlight this paragraph. In testing, Safari required the element to have a defined background color to start, but IE and FF were happy to fade back to whatever color that element inherited.

You can grab a copy of the snippet from GitHub. Did you find this helpful or have a better way of doing it? Let us know.

Peter Baumgartner

About the author

Peter Baumgartner

Peter is the founder of Lincoln Loop, having built it up from a small freelance operation in 2007 to what it is today. He is constantly learning and is well-versed in many technical disciplines including devops, …

View Peter's profile