http://jsfiddle.net/motocomdigital/gUWdJ/
I\'m after a jquery scroll technique please that I would like to adapt to my project.
Please see my
I went ahead and modified my script off of A. Wolf because I needed to make sure that my menu items lit up with a negative top difference instead of at 0. This works a lot better than creating a separate function and avoids having to create a click event for each menu item. I would also modify this script to account for the last item in the menu, it should be automatically highlighted if the second to last item is. I suppose mine is very similar but different as I handled my each loop outside of the my main highlight function. The other great thing about my modification is that accounts for having images inside of a link inside of a menu item and accounts for the height of a element and when the bottom of that element hits the top of the page, which is when the highlight should end before a new one does.
function highlight(item)
{
var itemTop = jQuery(item).position().top;
var windowTop = jQuery(window).scrollTop();
var topDifference = (windowTop - itemTop);
var itemHeight = jQuery(item).height();
var bottomDifference = topDifference - itemHeight;
var menuId = jQuery('#nav-icons li a').attr('href');
if (menuId = item)
{
if(topDifference > -1 && bottomDifference < 0)
{
jQuery("#nav-icons li a[href='" + item + "']").parent().addClass('active');
jQuery("#nav-icons li a[href!='" + item + "']").parent().removeClass('active');
}
else {
jQuery("#nav-icons li a[href='" + item + "']").parent().removeClass('active');
}
}
}
jQuery('#nav-icons li a').each(function(){
var eachAttr = jQuery(this).attr('href');
highlight(eachAttr);
});
If you wish a more generic function:
SEE DEMO
$(window).scroll(function() {
var windscroll = $(window).scrollTop();
if (windscroll >= 100) {
$('nav').addClass('fixed');
$('.wrapper section').each(function(i) {
if ($(this).position().top <= windscroll - 100) {
$('nav a.active').removeClass('active');
$('nav a').eq(i).addClass('active');
}
});
} else {
$('nav').removeClass('fixed');
$('nav a.active').removeClass('active');
$('nav a:first').addClass('active');
}
}).scroll();
You can do this way: http://jsfiddle.net/gUWdJ/1/
$(window).scroll(function() {
if ($(this).scrollTop() < $('section[data-anchor="top"]').offset().top) {
$('nav a').removeClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="top"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(0)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="news"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(1)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="products"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(2)').addClass('active');
}
if ($(this).scrollTop() >= $('section[data-anchor="contact"]').offset().top) {
$('nav a').removeClass('active');
$('nav a:eq(3)').addClass('active');
}
});