Reputation:
I have a div which I want to scroll up and down on page load and pause scrolling once the user hovers over the div. I have managed to get the div to scroll up and down however I cannot get it to pause.
Any Suggestions?
<div id="box" class="timeline container" style="overflow:scroll; width:100%; height:300px;">
//CONTENT
</div>
<script>
$("#box").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('#box').animate({scrollTop:0}, 4000);
},4000);
setInterval(function(){
$("#box").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('#box').animate({scrollTop:0}, 4000);
},4000);
},8000);
</script>
Upvotes: 2
Views: 1439
Reputation: 48415
I would suggest you don't use animate for the scroll feature. Instead just increment the scroll position every 100ms (or whatever).
You also need to add flags to determine scroll direction and pause state:
// global level variables.
var isPaused = false;
var direction = 1;
var element = $('#box');
// interval for scroll.
setInterval(function () {
if(!isPaused){
var pos = element.scrollTop();
var offset = 1 * direction;
element.scrollTop(pos + offset);
// Change the scroll direction when hit an end.
if ((element[0].scrollHeight - element.scrollTop() == element.outerHeight()) || (element.scrollTop() <= 0)) {
direction *= -1;
}
}
}, 100);
Then you can change the isPaused
flag when on mouseenter and mouseexit events, or use JQuery hover
event:
$('#box').hover(
function() {
isPaused = true;
}, function() {
isPaused = false;
}
);
Upvotes: 1
Reputation: 2550
You should be able to stop/pause your animation with the jQuery function stop()
: https://api.jquery.com/stop/
Upvotes: 0