Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
};
like image 441
Kevin mtk Avatar asked Apr 22 '15 16:04

Kevin mtk


2 Answers

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);
});
like image 162
Michael Irigoyen Avatar answered Sep 18 '22 23:09

Michael Irigoyen


This can be solved with just CSS using the :target pseudo-class. It allows you to highlight the item that has an ID matching the hash in your URL. A very simple example of this would be:

div {
    background-color: #00A087;
}
div:target {
   background-color: #F37736;
}

By default, a div would have a default colour but on finding a match it would switch to something different. To make it work in the way you specified, just sprinkle a bit of animation magic:

div {
    background-color: #00A087;
}
div:target {
    background-color: #F37736;
    animation-delay: 2s;
    animation-fill-mode: forwards;
    animation-duration: 4s;
    animation-name: highlight;
    animation-timing-function: ease-in-out;
}

@keyframes highlight {
    from {
        background-color: #F37736;
    }
    to {
        background-color: #00A087;
    }
}

Here I've set the animation to delay for 2 seconds and to maintain the final state of the animation.

With the various properties available you can mix and match to make it work a little differently but this would achieve what was being asked in the question.

Example on CodePen

like image 33
cchana Avatar answered Sep 20 '22 23:09

cchana