Skip to content

Instantly share code, notes, and snippets.

@jvandyke
Created March 13, 2013 14:55
Show Gist options
  • Save jvandyke/5152893 to your computer and use it in GitHub Desktop.
Save jvandyke/5152893 to your computer and use it in GitHub Desktop.
Scrollspy for Coffeescript and not for Bootstrap
$ = jQuery
$.fn.scrollwatch = () ->
# Cache selectors
lastId = undefined
topMenu = $(this)
isInitialized = topMenu.data('scrollwatch') is true
topMenuHeight = 0 #topMenu.outerHeight() + 15
# All list items
menuItems = topMenu.find("a")
# Anchors corresponding to menu items
scrollItems = menuItems.map(->
item = $($(this).attr("href"))
item if item.length
)
# Unbind existing scrollwatchers
menuItems.off 'click.scrollwatch'
# Bind click handler to menu items
# so we can get a fancy scroll animation
menuItems.on 'click.scrollwatch', (e) ->
href = $(this).attr("href")
offsetTop = (if href is "#" then 0 else $(href).offset().top - topMenuHeight + 1)
$("html, body").stop().animate
scrollTop: offsetTop
, 300
e.preventDefault()
# Unbind last scroll
if (isInitialized)
$(window).off 'scroll.scrollwatch'
# Bind to scroll
$(window).on 'scroll.scrollwatch', () ->
# Get container scroll position
fromTop = $(this).scrollTop() + topMenuHeight
# Get id of current scroll item
cur = scrollItems.map(->
return this if $(this).offset().top < fromTop
)
# Get the id of the current element
cur = cur[cur.length - 1]
id = (if cur and cur.length then cur[0].id else "")
if id and lastId isnt id
lastId = id
# Set/remove active class
menuItems.parent().removeClass("active")
menuItems.filter("[href=#" + id + "]").parent().addClass "active"
# topMenu.data 'scrollwatch-scrollfn', watchItemsFn
topMenu.data 'scrollwatch', true
@jvandyke
Copy link
Author

scrollwatch for Coffeescript.

Alot like Bootstrap's scrollSpy, but easier to understand and implement.

Usage
$('#elementToUpdate').scrollwatch()

The #elementToWatch might be your navigation bar, but it can be anything. The only requirement is that it contains anchors (<a href="#id">) that reference IDs of other elements on the page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment