Skip to content

Instantly share code, notes, and snippets.

@zaurmag
Last active August 7, 2016 18:27
Show Gist options
  • Save zaurmag/0531dd203390afb65053933737db39f7 to your computer and use it in GitHub Desktop.
Save zaurmag/0531dd203390afb65053933737db39f7 to your computer and use it in GitHub Desktop.
Выделение пункта меню Skroll Spy
// ======= Scroll Spy Menu =======
var lastId,
topMenu = jQuery("#main-menu"),
topMenuHeight = topMenu.outerHeight(),
menuItems = topMenu.find("a"),
scrollItems = menuItems.map(function() {
var item = jQuery(jQuery(this).attr("href"));
if (item.length) {
return item;
}
});
menuItems.click(function(e) {
var href = jQuery(this).attr("href"),
offsetTop = href === "#" ? 0 : jQuery(href).offset().top - topMenuHeight + 1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 600);
e.preventDefault();
});
jQuery(window).scroll(function() {
var fromTop = jQuery(this).scrollTop() + topMenuHeight;
var cur = scrollItems.map(function() {
if (jQuery(this).offset().top < fromTop)
return this;
});
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment