public
Created

  • Download Gist
index.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
# "affix" and "scrollspy", before bootstrap had them:
$ ->
$nav = $('nav')
navTop = $nav.offset?().top - 12
navFixed = 0
sections = {}
for section in $('section')
$section = $(section)
id = $section.attr('id')
if id
offset = $section.offset()
sections[id] = offset.top + offset.height
 
setNavPos = (scrollPos) ->
if scrollPos >= navTop and navFixed is 0
$nav.addClass('nav-fixed')
$nav.css({width: $nav.parent().width()})
navFixed = 1
else if scrollPos <= navTop and navFixed is 1
$nav.removeClass('nav-fixed')
$nav.css({width: undefined})
navFixed = 0
 
setCurrentSection = (scrollPos) ->
current = ((section) for section, offset of sections when scrollPos - offset < 0)[0]
$nav.find("li").removeClass('active')
$nav.find("li > a[href=##{current}]").parent().addClass('active')
 
$win.resize ->
navFixed = -1
setNavPos($win.scrollTop())
 
$win.scroll ->
scrollPos = $win.scrollTop()
setNavPos(scrollPos)
setCurrentSection(scrollPos)
 
$nav.delegate 'li > a', 'click', (event) ->
event.preventDefault()
$dest = $($(this).attr('href'))
$win.scrollTop($dest.offset()?.top)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.