scroll inspector by rel
by zalog
HTML
<ul id="menu-main">
<li class="active"><a href="#" rel="home">Home</a></li>
<li><a href="#" rel="projects">Projects</a></li>
<li><a href="#" rel="contact">Contact</a></li>
</ul>
<div id="content">
<div id="home" class="page">
Page Home
</div>
<div id="projects" class="page">
Page projects
</div>
<div id="contact" class="page">
Page contact
</div>
</div>
CSS
UL { position:fixed }
LI { display:inline }
LI.active A { color:red }
#content { padding:20px 0 0 0 }
.page { padding:0 0 1000px 0 }
JavaScript
/* scroll inspector #menu-main
*********************************************************************/
// Cache selectors
var lastId,
topMenu = jQuery("#menu-main"),
topMenuHeight = topMenu.outerHeight(),
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = jQuery('#'+jQuery(this).attr("rel"));
if (item.length) { return item; }
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("rel"), offsetTop = href === "#" ? 0 : jQuery('#'+href).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems.parent().removeClass("active").end().filter("[rel="+id+"]").parent().addClass("active");
}
});