Created
September 25, 2012 16:24
-
-
Save yumitsu/3782934 to your computer and use it in GitHub Desktop.
jQuery scroller, like bootstrap scrollspy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function(){ | |
var lastId, topMenu = $("#navbar-scroll"), | |
topMenuHeight = topMenu.outerHeight() + 150, | |
menuItems = topMenu.find("a"), | |
scrollItems = menuItems.map(function() { | |
var item = $($(this).attr("href")); | |
if (item.length) { | |
return item; | |
} | |
}); | |
menuItems.click(function(e) { | |
var href = $(this).attr("href"), | |
topMenuHeight = topMenu.outerHeight() + 20, | |
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1; | |
$('html, body').stop().animate({ | |
scrollTop: offsetTop | |
}, 300); | |
e.preventDefault(); | |
}); | |
$(window).scroll(function() { | |
var fromTop = $(this).scrollTop() + topMenuHeight; | |
var cur = scrollItems.map(function() { | |
if ($(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