Skip to content

Instantly share code, notes, and snippets.

@mixonic
Created April 11, 2012 03:15
Show Gist options
  • Save mixonic/2356631 to your computer and use it in GitHub Desktop.
Save mixonic/2356631 to your computer and use it in GitHub Desktop.
Nice nav & scrolling
$ () ->
scrolls = $('.scroll')
if scrolls.length
scrolls.click (e) ->
href = $(this).attr('href')
fragments = href.split('#')
if fragments.length > 1 && fragments[0] == "#{window.location}".split('#')[0]
e.preventDefault()
$('html,body').animate({scrollTop: $("a[name=#{fragments[fragments.length-1]}]").offset().top}, {duration: 'fast', complete: () ->
window.location = href
})
scrolled = false
$(window).scroll () ->
scrolled = true
setInterval( () ->
return unless scrolled
scrolled = false
top = $(window).scrollTop()
return unless top > 0
rev_scrolls = scrolls.get().reverse()
if $(document).height() == (top + $(window).height())
anchor = $(rev_scrolls[0])
unless anchor.parent('li').hasClass('selected')
anchor.parent('li').addClass('selected')
if window.history && window.history.replaceState
window.history.replaceState({}, null, anchor.attr('href'))
$(rev_scrolls).each (i) ->
if i > 0
$(this).parent('li').removeClass('selected')
else
used = false
$(rev_scrolls).each () ->
anchor = $(this)
fragments = anchor.attr('href').split('#')
if fragments.length > 1
if !used && (top+10) > ($("a[name=#{fragments[fragments.length-1]}]").offset().top)
unless anchor.parent('li').hasClass('selected')
anchor.parent('li').addClass('selected')
if window.history && window.history.replaceState
window.history.replaceState({}, null, anchor.attr('href'))
used = true
else
anchor.parent('li').removeClass('selected')
, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment