Skip to content

Instantly share code, notes, and snippets.

@roseg43
Created December 13, 2016 20:25
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 roseg43/479b6b2141809e0ca17f8eab2ce624bc to your computer and use it in GitHub Desktop.
Save roseg43/479b6b2141809e0ca17f8eab2ce624bc to your computer and use it in GitHub Desktop.
A small class that creates a list of page-scrolling anchors based on sections with data-nav-title set.
function anchorNavigation(el) {
var self = this;
this.$el = jq(el);
this.$navigableItems = jq('[data-nav-title]');
this.$el.append('<ul />');
this.$navigationList = this.$el.find('ul');
this.navigationItems = [];
self.populateNavigation();
}
anchorNavigation.prototype.populateNavigation = function() {
var self = this;
// Map this.navigableItems, rendering each item into this.el
this.$navigableItems.map(function() {
var title = jq(this).data('nav-title');
var newItem = self.$navigationList.append('<li><a href="javascript:void(0);">' + title + '</a></li>');
this.id = self.parseStringToId(title);
});
self.refreshItems();
}
anchorNavigation.prototype.refreshItems = function() {
this.navigationItems = this.$el.find('li');
this.registerEvents();
}
anchorNavigation.prototype.registerEvents = function() {
var self = this;
self.navigationItems.click(function(e) {
e.preventDefault();
var $this = jq(this);
var title = $this.find('a').text();
var scrollId = self.parseStringToId(title);
self.scrollToItem(scrollId);
});
}
anchorNavigation.prototype.scrollToItem = function(id) {
jq('html,body').animate({
scrollTop: jq('#' + id).offset().top
}, 'slow');
}
anchorNavigation.prototype.parseStringToId = function(string) {
return string.replace(/[\s\?\(\)]+/g, '').toLowerCase();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment