Skip to content

Instantly share code, notes, and snippets.

@axelav
Forked from alxhill/scrollspy.coffee
Last active January 4, 2016 15:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save axelav/8639402 to your computer and use it in GitHub Desktop.
Save axelav/8639402 to your computer and use it in GitHub Desktop.
add smooth scrolling (lines 11-18) & allow nested lists of spies
angular.module('directives.scrollSpy', [])
.directive('spy', ($location) ->
restrict: 'A'
require: '^scrollSpy'
link: (scope, elem, attrs, scrollSpy) ->
attrs.spyClass ?= 'active'
elem.click (e) ->
e.stopPropagation()
if attrs.spy
target = $('#' + attrs.spy)
speed = 750
$('html, body').stop().animate
scrollTop: target.offset().top + 1
speed
easeInOutCubuc = (x, t, b, c, d) ->
c * ((t = t / d - 1) * t * t + 1) + b
else
$('html, body').stop().animate scrollTop: 0, speed
scrollSpy.addSpy
id: attrs.spy
in: ->
elem.addClass attrs.spyClass
elem.parents('li').addClass attrs.spyClass
out: -> elem.removeClass attrs.spyClass
)
.directive('scrollSpy', ($window, $timeout) ->
restrict: 'A'
controller: ($scope) ->
$scope.spies = []
@addSpy = (spyObj) ->
$scope.spies.push spyObj
return
scope: true
link: (scope, elem, attrs) ->
spyElems = []
topBuffer = if attrs.topBuffer then attrs.topBuffer else 0
scope.$watchCollection '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()
if !spyElems[spy.id]? or spyElems.length is 0
spyElems[spy.id] = elem.find('#' + spy.id)
if spyElems[spy.id]? and spyElems[spy.id].length isnt 0
# TODO: fix for IE9+ ?
# https://gist.github.com/alxhill/6886760#comment-952714
if (pos = spyElems[spy.id].offset().top) - $window.pageYOffset <= topBuffer
# if (pos = spyElems[spy.id].offset().top) - $window.scrollY <= topBuffer
spy.pos = pos
highlightSpy ?=spy
if highlightSpy.pos < spy.pos
highlightSpy = spy
highlightSpy?.in()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment