Skip to content

Instantly share code, notes, and snippets.

@alxhill
Created October 8, 2013 15:44
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save alxhill/6886760 to your computer and use it in GitHub Desktop.
Save alxhill/6886760 to your computer and use it in GitHub Desktop.
Updated version of Angular ScrollSpy
angular.module('jobFoundryDirectives').directive 'spy', ($location) ->
restrict: "A"
require: "^scrollSpy"
link: (scope, elem, attrs, scrollSpy) ->
attrs.spyClass ?= "current"
elem.click ->
scope.$apply ->
$location.hash(attrs.spy)
scrollSpy.addSpy
id: attrs.spy
in: -> elem.addClass attrs.spyClass,
out: -> elem.removeClass attrs.spyClass
angular.module('jobFoundryDirectives').directive 'scrollSpy', ($window) ->
restrict: 'A'
controller: ($scope) ->
$scope.spies = []
@addSpy = (spyObj) -> $scope.spies.push spyObj
link: (scope, elem, attrs) ->
spyElems = []
scope.$watch 'spies', (spies) ->
for spy in spies
unless spyElems[spy.id]?
spyElems[spy.id] = elem.find('#'+spy.id)
$($window).scroll ->
highlightSpy = null
for spy in scope.spies
spy.out()
# the elem might not have been available when it was originally cached,
# so we check again to get another element in case this one doesn't exist.
spyElems[spy.id] =
if spyElems[spy.id].length is 0
elem.find('#'+spy.id)
else
spyElems[spy.id]
# the element could still not exist, so we check first to avoid errors
if spyElems[spy.id].length isnt 0
if (pos = spyElems[spy.id].offset().top) - $window.scrollY <= 0
spy.pos = pos
highlightSpy ?= spy
if highlightSpy.pos < spy.pos
highlightSpy = spy
highlightSpy?.in()
@nwpappas
Copy link

I did a JavaScript translation of this CoffeeScript and made a few updates. You can find the updates here: https://gist.github.com/EvilClosetMonkey/9194765

What changed:

  1. Catch the case where a menu spy definition does not have an associated content id defined.
  2. Select the last menu spy item if the browser is scrolled all the way to the bottom (content length sometimes prevent this from happening).
  3. Changed the class to active to match Bootstrap's CSS.

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