Skip to content

Instantly share code, notes, and snippets.

@simshanith
Last active December 15, 2015 06:19
Show Gist options
  • Save simshanith/5215698 to your computer and use it in GitHub Desktop.
Save simshanith/5215698 to your computer and use it in GitHub Desktop.
Progressively enhanced cross-browser scrolling, via Modernizr, jQuery Transit, and classic $.scrollTo fallback
var sliding = false; // variable outside function scope to detect a slide is in progress
function slideTo(target, duration){ // credit to Mahieddine Abdelkader & Ludwig Wendzich for original ideas.
var to = isNaN(target) ? $(target).offset().top : target, //find scroll to position
from = $(window).scrollTop() //find starting point
dy = to-from, //calculate change in scroll position - deltaY
body = $("body"), // TODO: better to have it outside of local scope already rather than fetching it every time...
duration = isNaN(duration) ? 500 : duration;
// We're going to use translate-y to move the the page so it feels like we're at the *from* scroll position, when we're actually instantly at the *to* scroll position. */
if(sliding){
// if already sliding, keep on animating towards translate-y: 0 & reset scrollTop.
// Might cause some jump.
$(window).scrollTop(to);
} else {
body.css({y: dy});
$(window).scrollTop(to);
body.transition({
y: 0,
duration: duration,
complete: function(){
body.css("transition", "none"); // reset transition (may be managed by transit; but doesn't hurt to do it explicitly)
sliding = false; // toggle
}
});
sliding = true; // toggle
}
}
function windowScroll(target, duration){
duration = isNaN(duration) ? 500 : duration;
if(Modernizr.csstransitions && Modernizr.csstransforms){ // test for requisite CSS3 features
slideTo(target, duration);
} else { // fallback to $.scrollTo
var to = isNaN(target) ? target : {top: target, left: "+=0"};
$.scrollTo(target, {duration: duration});
}
}
$('#slideTop').on('click', function(){windowScroll(0, 2000);});
@simshanith
Copy link
Author

Dependencies

jQuery
Modernizr
jQuery scrollTo Plugin
//cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/1.4.3/jquery.scrollTo.min.js
jQuery Transit plugin
//cdnjs.cloudflare.com/ajax/libs/jquery.transit/0.9.9/jquery.transit.min.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment