How can I highlight a specific div from a hash in the URL?

When a user comes to a website via www.example.com/#div4, I would like the division specified in the URL to be highlighted with #F37736 (orange) and then within 2 seconds transition smoothly back to #00A087 (the default color).

The div to be highlighted as a class of “fixed-nav-bar”.

What I’ve tried:

var hash = false; 
checkHash();

function checkHash(){ 
  if(window.location.hash != hash) {
    hash = window.location.hash; 
  } t=setTimeout("checkHash()",400); 
};

Answer

You could look for the hash, then target the division by it’s class name. You’ll immediately change the color of the div to your orange color, then animate it back to your default color.

You will need to include the jQuery Color library to animate the background-color though, as vanilla jQuery cannot animate background-color. You can also use jQuery UI’s highlight effect, thought the UI library is a little heavier in size.

$(document).ready(function () {
    var hash = window.location.hash;
    $('.' + hash).css('background-color', '#F37736').animate({
        backgroundColor: '#00A087'
    }, 2000);
});

Leave a Reply

Your email address will not be published. Required fields are marked *