I have a C# MVC Web App that displays a scrolling schedule for display on digital signage. It uses the JQuery animate function to scroll back up to the top when it reaches the bottom (looping continuously while it's running). I'll explain the running of the app step-by-step.
When the app is started it scrolls to the bottom like normal, then animates back to the top, however with certain settings, on the second pass and every time after it will get stuck a little bit after scrolling out of the initial view. The app will then scroll back to the top, then scroll down to the bottom normally. This is the bounce. The issue seems to happen when the animate function is set to be slower (using 'slow' or a higher value like 3000).
Here is the code governing the scrolling to the bottom and the animate back to the top:
$(document).ready(function () {
var div = $('#docket');
var scrollDown = setInterval(function () {
var pos = div.scrollTop();
div.scrollTop(pos + 2);
}, 75)
// Check if we are at the bottom. If so, wait 1 second and scroll to the top.
div.bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
div.delay(1000).animate({ scrollTop: 0 }, 'slow');
}
})
});
EDIT 1 I've done some additional investigation as the issue is still occurring. I think it may be related to the timing of the delay() and the setInterval() but so far the issue has proved to be tough to get a handle on. I added some alerts so I could easily tell when the script will start the scrolling to the top. To my surprise, I noticed they were not triggered when the bounce occurs, only on the initial (and correct) scroll to the top. I'm not super familiar with JQuery so I'm kind of throwing things at the wall and seeing if they stick right now.
EDIT 2 Using part of the code from this answer Callback of .animate() gets called twice jquery. I've found that my #docket div is being animated on twice. The fix in that answer doesn't prevent the bounce from occurring though. Here is the most updated version with the code from the linked answer. Done animating docket alert is displayed twice.
$(document).ready(function () {
var div = $('#docket');
var scrollDown = setInterval(function () {
var pos = div.scrollTop();
div.scrollTop(pos + 2);
}, 50)
// Check if we are at the bottom. If so, wait 1 second and scroll to the top.
div.bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() == this.scrollHeight) {
div.delay(100).animate({ scrollTop: 0 }, 'slow', function() {
// Called per element
alert("Done animating " + this.id);
}).promise().then(function() {
// Called when the animation in total is complete
alert("Completed animation");
});
}
})
});