Last active
December 15, 2015 06:19
-
-
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
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 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);}); |
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
Demo with more fx
http://webpop.simloovoo.com/
Source JS
http://webpop.simloovoo.com/js/script.js