Reputation: 57
I'd like to try to achieve an effect of loop scroll the page. I found this script that to which I have made some changes as the scroll 1px loading so as to enable the loop.
Should I apply this effect within a div ... but I can not figure out what to change the code to make it work.
It helped to turn the loop inside the wrapper div?
$(document).ready(function() {
$('body').height( WRHeight + $(window).height() );
$(window).scroll(function() {
if ( $(window).scrollTop() >= ($('body').height() - $(window).height()) ) {
$(window).scrollTop(1);
}
else if ( $(window).scrollTop() == 0 ) {
$(window).scrollTop($('body').height() - $(window).height() -1);
}
});
Upvotes: 3
Views: 1059
Reputation: 120
I've re-implemented the script and added some comments to hopefully make it more clear:
// Container element which has a scrollbar
var $c = $("#container");
// Child element which is taller than the container
var $e = $("#element");
// The point at which the page will loop when scrolling down
var loopPoint = $e.height() - $c.height();
// Define a function which runs whenever the scroll position of $c changes
$c.scroll(function () {
// If the new scroll position matches our loop point
if ($c.scrollTop() === loopPoint) {
// Scroll to (almost) the the top ('0' would be the top; we do this so we don't loop back again instantly)
$c.scrollTop(1);
}
// Otherwise, if the new scroll position = the top of the element
else if ($c.scrollTop() === 0) {
// Scroll to (almost) the bottom, we can use (our loop point - 1)
$c.scrollTop(loopPoint - 1);
}
});
Here's a JSfiddle for you: http://jsfiddle.net/cjmoran/2do67um8/
Note: I've noticed that this approach can break middle-click scrolling in Chrome pretty badly, to the point that JSfiddle crashes. There may be a better way to implement this so that doesn't happen. Appears to work fine in the latest version of Firefox, but those are the only browsers I tested.
Upvotes: 2