user1374796 user1374796 - 1 year ago 85
CSS Question

jQuery: highlight nav when div scrolls into view

I have a simple side navigation of circular divs, clicking on one scrolls you to the relevant

div, this all works just fine. Now though I'm wondering if it's possible to highlight the relevant
div, dependant upon which
div is in view.

e.g. if
comes into view, the relevant
div with the
will be highlighted
background-color: blue

jsFiddle demo:


<div id="block-one" class="block"></div>
<div id="block-two" class="block"></div>
<div id="block-three" class="block"></div>
<div id="block-four" class="block"></div>
<div id="block-five" class="block"></div>

<ul class="nav-wrap">
<li class="nav-item" data-hook="one"></li>
<li class="nav-item" data-hook="two"></li>
<li class="nav-item" data-hook="three"></li>
<li class="nav-item" data-hook="four"></li>
<li class="nav-item" data-hook="five"></li>


$(document).ready(function () {


//Every resize of window
$(window).resize(function () {

//Dynamically assign height
function Resize() {
// Handler for .ready() called.
var divwid = $(window).height() / 2,
navhei = $('.nav-wrap').height() / 2,
newhei = divwid - navhei;
'top': newhei


$('.nav-item').click(function () {
$('html, body').animate({
scrollTop: $('#block-' + $(this).attr('data-hook')).offset().top - 0
}, "slow");

If this is at all possible? Any suggestions would be greatly appreciated!

Answer Source

Adding a class selected in your css like that:

.nav-item:hover, .nav-item.selected {
     background-color: blue;

You can bind a function on the scroll event to change the color of the current nav-item:

function hoverCurrentItem() {
    var h = $(".block:first").height();
    var sIndex = Math.floor($(window).scrollTop() / h);
    var $sItem = $(".nav-item").eq(sIndex);
    if (!$sItem.hasClass("selected")) {

$(window).scroll(function(e) {

View in JsFiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download