Last active
September 28, 2015 21:29
-
-
Save cange/1499127 to your computer and use it in GitHub Desktop.
Simple smooth scrolling solution
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
var SmoothScroll = function () { | |
'use strict'; | |
var self = this, | |
$topReference = $('html, body'), | |
$window = $(window) | |
; | |
function targetPosition(targetHash) { | |
// Escape any exclamation mark that might be present on the hash and is not a valid selector | |
// e.g. "#!edit" | |
targetHash = targetHash.replace(/(\!)/g, '\\$1'); | |
var verticalOffset = 10, | |
topOffset = verticalOffset, | |
$target = $(targetHash), | |
position = 0 | |
; | |
return Math.round( ( $target[0] ? $target.offset().top : 0 ) - topOffset ); | |
} | |
function goToTarget(targetHash) { | |
var yCoord; | |
if (targetHash) { | |
yCoord = targetPosition(targetHash); | |
// Triggering it right away fixes ambiguos behavior on IE9 | |
window.scrollTo(0, yCoord); | |
// Safari needs a small delay before you can execute the scroll position | |
// This is way the scrolling is triggered again after a brief delay | |
setTimeout(function () { | |
$window.scrollTop(yCoord); | |
}, 1); | |
} | |
} | |
function pushHistoryState(targetHash) { | |
if (Modernizr.history) { | |
var location = window.location, | |
pathSegments = location.pathname.split(/\//g), | |
path = pathSegments[pathSegments.length], | |
stateObj = {}, | |
title = '', | |
url = location.pathname + location.search + targetHash | |
; | |
stateObj[path] = targetHash.replace(/^#/, ''); | |
history.pushState(stateObj, title, url); | |
} | |
} | |
function scrollHandler(event) { | |
event.preventDefault(); | |
var targetHash = $(this).attr('href'), | |
duration = 800, | |
easing = 'swing',//'easeOutQuad', | |
position = targetPosition(targetHash) | |
; | |
$topReference | |
.stop() | |
.animate({scrollTop: position}, duration, easing, function () { | |
pushHistoryState(targetHash); | |
}) | |
; | |
} | |
/** | |
* @constructor | |
*/ | |
self.initialize = function () { | |
$('.js-smoothscroll').on('click', scrollHandler); | |
goToTarget(window.location.hash); | |
} | |
self.initialize(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment