-
-
Save axelav/8639402 to your computer and use it in GitHub Desktop.
add smooth scrolling (lines 11-18) & allow nested lists of spies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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