Skip to content

Instantly share code, notes, and snippets.

@mattly
Created September 24, 2012 02:39
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 mattly/3773912 to your computer and use it in GitHub Desktop.
Save mattly/3773912 to your computer and use it in GitHub Desktop.
# "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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment