user1374796 user1374796 - 3 months ago 9
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

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

e.g. if
#block-3
comes into view, the relevant
.nav-item
div with the
data-hook="3"
will be highlighted
background-color: blue
.


jsFiddle demo: http://jsfiddle.net/rf4Ea/3/


HTML:

<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>
</ul>


jQuery:

$(document).ready(function () {

Resize();
});

//Every resize of window
$(window).resize(function () {
Resize();
});

//Dynamically assign height
function Resize() {
// Handler for .ready() called.
var divwid = $(window).height() / 2,
navhei = $('.nav-wrap').height() / 2,
newhei = divwid - navhei;
$('.nav-wrap').css({
'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

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")) {
        $(".selected").removeClass("selected");
        $sItem.addClass("selected");
    }    
}
hoverCurrentItem();

$(window).scroll(function(e) {
    hoverCurrentItem()
});

View in JsFiddle

Comments