/* * jquery one page nav plugin * http://github.com/davist11/jquery-one-page-nav * * copyright (c) 2010 trevor davis (http://trevordavis.net) * dual licensed under the mit and gpl licenses. * uses the same license as jquery, see: * http://jquery.org/license * * @version 0.9 * * example usage: * $('#nav').onepagenav({ * currentclass: 'current', * changehash: false, * scrollspeed: 750 * }); */ ;(function($) { $.fn.onepagenav = function(options) { var opts = $.extend({}, $.fn.onepagenav.defaults, options), onepagenav = {}; onepagenav.sections = {}; onepagenav.bindnav = function($el, $this, o) { var $par = $el.parent(), newloc = $el.attr('href'), $win = $(window); if(!$par.hasclass(o.currentclass)) { if(o.begin) { o.begin(); } onepagenav.adjustnav($this, $par, o.currentclass); $win.unbind('.onepagenav'); $.scrollto(newloc, o.scrollspeed, { easing: o.easing, offset: { top: -o.scrolloffset }, onafter: function() { if(o.changehash) { window.location.hash = newloc; } $win.bind('scroll.onepagenav', function() { onepagenav.scrollchange($this, o); }); if(o.end) { o.end(); } } }); } }; onepagenav.adjustnav = function($this, $el, curclass) { $this.find('.'+curclass).removeclass(curclass); $el.addclass(curclass); }; onepagenav.getpositions = function($this, o) { var $nav = $this.find('a'); if(o.filter !== '') { $nav = $nav.filter(o.filter); } /*$nav.each(function() { var linkhref = $(this).attr('href'); var divpos = $(linkhref).offset(); var toppos = divpos.top; onepagenav.sections[linkhref.substr(1)] = math.round(toppos) - o.scrolloffset; });*/ }; onepagenav.getsection = function(windowpos, o) { var returnvalue = '', windowheight = math.round($(window).height() * o.scrollthreshold); for(var section in onepagenav.sections) { if((onepagenav.sections[section] - windowheight) < windowpos) { returnvalue = section; } } return returnvalue; }; onepagenav.scrollchange = function($this, o) { onepagenav.getpositions($this, o); var windowtop = $(window).scrolltop(), position = onepagenav.getsection(windowtop, o); if(position !== '') { onepagenav.adjustnav($this,$this.find('a[href=#'+position+']').parent(), o.currentclass); } }; onepagenav.init = function($this, o) { var didscroll = false, $nav = $this.find('a'); if(o.filter !== '') { $nav = $nav.filter(o.filter); } $nav.bind('click', function(e) { onepagenav.bindnav($(this), $this, o); e.preventdefault(); }); onepagenav.getpositions($this, o); $(window).bind('scroll.onepagenav', function() { didscroll = true; }); setinterval(function() { if(didscroll) { didscroll = false; onepagenav.scrollchange($this, o); } }, 250); }; return this.each(function() { var $this = $(this), o = $.meta ? $.extend({}, opts, $this.data()) : opts; onepagenav.init($this, o); }); }; // default options $.fn.onepagenav.defaults = { currentclass: 'current', changehash: false, easing: 'swing', filter: '', scrollspeed: 750, scrolloffset: 0, scrollthreshold: 0.5, begin: false, end: false }; })(jquery);