Skip to content

Instantly share code, notes, and snippets.

@teramako
Created September 26, 2011 10:35
Show Gist options
  • Save teramako/1241994 to your computer and use it in GitHub Desktop.
Save teramako/1241994 to your computer and use it in GitHub Desktop.
ページ内リンクをスムーズスクロールしつつpushState
(function () {
var util = {
requestAnimationFrame: (function() {
if ("mozRequestAnimationFrame" in window)
return window.mozRequestAnimationFrame.bind(window);
else if ("webkitRequestAnimationFrame" in window)
return window.webkitRequestAnimationFrame.bind(window);
else {
return function (callback) {
window.setTimeout(callback, 1000/60);
}
}
})(),
get scrollMaxY () {
return document.documentElement.getBoundingClientRect().height - window.innerHeight;
},
};
window.addEventListener("click", onLinkClick, true);
window.onpopstate = function (aEvent) {
if (aEvent.state && ("y" in aEvent.state)) {
animationScroll(aEvent.state.y, window.location.hash);
}
}
function onLinkClick (aEvent) {
var source = aEvent.target;
if (!(source instanceof HTMLAnchorElement))
return;
var href = source.getAttribute("href");
if (href.indexOf("#") !== 0)
return;
aEvent.preventDefault();
aEvent.stopPropagation();
var id = href.substr(1);
var target = document.getElementById(id);
animationScroll(target.getBoundingClientRect().top + window.scrollY, id, true);
}
function animationScroll (aY, aID, pushHistory) {
var currentScrollY = window.scrollY;
var targetScrollY = Math.min(aY, util.scrollMaxY);
function step() {
var s = targetScrollY - window.scrollY;
window.scrollBy(0, s / 4);
if (-4 <= s && s <= 4) {
window.scrollTo(0, targetScrollY);
if (pushHistory) {
history.replaceState({y: currentScrollY}, "", window.location.hash);
history.pushState({y: targetScrollY}, "", aID ? "#" + aID : "");
}
} else {
util.requestAnimationFrame(step);
}
}
util.requestAnimationFrame(step);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment