I want to detect which element is visible on the screen when scrolling down/up. I have to set as active menu item on the menu which targets that element.
// must have a page class
$('.page').each(function(){
$positionData[$(this).attr('id')] = $(this).offset().top;
});
$(document).scroll(function(){
var $position = $(this).scrollTop();
if($position > $height && !$body.hasClass('scrolled')) {
$body.addClass('scrolled');
//detech the scroll is between an element offset
} else if($position < $height) {
$body.removeClass('scrolled');
}
});
Any idea?
For Bootstrap users;
There is a component already can be found named Scrollspy.
Scrollspy
How to use?
1: Add relative positioning to body.
2: Add data-spy="scroll" and data-target="" attributes to your body. (data-target must target your menu)
3: Set your menu. Don't for get to add nav class to your ul/ol element.
4: Check your target elements to every element must have an id attribute same as your link targets.