diff --git a/lib/angular-smooth-scroll.js b/lib/angular-smooth-scroll.js index 3c81440..8b4356d 100644 --- a/lib/angular-smooth-scroll.js +++ b/lib/angular-smooth-scroll.js @@ -36,7 +36,7 @@ callbackBefore = options.callbackBefore || function() {}, callbackAfter = options.callbackAfter || function() {}, container = document.getElementById(options.containerId) || null, - containerPresent = (container != undefined && container != null); + containerPresent = (container !== undefined && container !== null); /** * Retrieve current location @@ -102,42 +102,32 @@ distance = endLocation - startLocation, percentage, position, - scrollHeight, - internalHeight; + scrollHeight = containerPresent ? container.scrollHeight : document.body.scrollHeight, + startTime, + internalHeight, + innerHeight = containerPresent ? container.clientHeight : window.innerHeight; /** * Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page) */ - var stopAnimation = function () { - currentLocation = getScrollLocation(); - internalHeight = window.innerHeight + currentLocation; - if(containerPresent) { - scrollHeight = container.scrollHeight; - } else { - scrollHeight = document.body.scrollheight; - } + var stopAnimation = function (position) { + currentLocation = position; + internalHeight = innerHeight + currentLocation; - if ( - ( // condition 1 - position == endLocation - ) || - ( // condition 2 - currentLocation == endLocation - ) || - ( // condition 3 - internalHeight >= scrollHeight - ) - ) { // stop - clearInterval(runAnimation); + if ((position == endLocation) || (currentLocation == endLocation) || + (internalHeight >= scrollHeight)) { + cancelAnimationFrame(runAnimation); callbackAfter(element); - } + } else { + requestAnimationFrame(animateScroll); + } }; /** * Scroll the page by an increment, and check if it's time to stop */ - var animateScroll = function () { - timeLapsed += 16; + var animateScroll = function (now) { + timeLapsed = now - startTime; percentage = ( timeLapsed / duration ); percentage = ( percentage > 1 ) ? 1 : percentage; position = startLocation + ( distance * getEasingPattern(easing, percentage) ); @@ -146,11 +136,12 @@ } else { window.scrollTo( 0, position ); } - stopAnimation(); + stopAnimation(position); }; callbackBefore(element); - var runAnimation = setInterval(animateScroll, 16); + startTime = performance.now(); + var runAnimation = requestAnimationFrame(animateScroll); }, 0); }; @@ -267,4 +258,4 @@ }; }]); -}()); \ No newline at end of file +}());