Skip to content

Instantly share code, notes, and snippets.

@robinclart
Created March 3, 2013 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinclart/5078025 to your computer and use it in GitHub Desktop.
Save robinclart/5078025 to your computer and use it in GitHub Desktop.
Navigation highlighting for one page website
(function() {
var Nav;
Nav = (function() {
function Nav(selector) {
this.selector = selector;
this.element = $(this.selector || "[data-nav]").first();
this["class"] = this.element.data("nav");
this.height = this.element.parent().height();
this.links = this.element.find("a");
this.link = null;
this.offsets = $.map(this.links, function(link) {
return $($(link).attr("href")).offset().top;
});
this.onScroll();
this.bindEvents();
}
Nav.prototype.bindEvents = function() {
return $(document).on("scroll", $.proxy(this.onScroll, this));
};
Nav.prototype.onScroll = function() {
var currentLink, scrolled,
_this = this;
scrolled = $(document).scrollTop();
this.link = this.links.first();
$.each(this.offsets, function(index, offset) {
if (offset < (scrolled + _this.height)) {
return _this.link = _this.links.get(index);
}
});
currentLink = $(this.link);
if (!currentLink.hasClass(this["class"])) {
$("." + this["class"]).removeClass(this["class"]);
return currentLink.addClass(this["class"]);
}
};
return Nav;
})();
window.Nav = Nav;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment