Search code examples
javascriptjqueryhtmlcssscroll

how to scroll automatically up and down a div continuously


I am working on html page where i have a div called divContainer. I want to scroll this div continuously up and down automatically. For this I used the following code:

$(document).ready(function() {
  var interval = setInterval(function() {
    if ($("#divContainer").scrollTop() != $('#divContainer')[0].scrollHeight) {
      $("#divContainer").scrollTop($("#divContainer").scrollTop() + 10);
    } else {
      clearInterval(interval);
    }
  }, 100);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="divContainer" style="height:950px;overflow:auto"></div>

However this code scrolls the div from top to bottom but not from bottom to top. I also want to scroll up and down continuously. How can I achieve this?


Solution

  • It can be done simply by storing the direction you're moving and switching when reaching the top/bottom. The easiest way to check if we need to switch is to see if the position has actually changed since the last iteration.

    If you try to scroll to a position by passing in a too small or large number, the position will be set right to the top or bottom respectively. In this case scrollTop() will return the same number as before, and we'll know it's time to switch direction.

    var up = false;
    var lastPosition;
    
    var interval = setInterval(function () {
        var $container = $("#divContainer");
        var position = $container.scrollTop();
        var height = $container[0].scrollHeight;
    
        // If we haven't moved, switch direction
        if(position === lastPosition) up = !up;
        lastPosition = position;
    
        if (up) {
            // Going up
            $container.scrollTop(position - 10);
        } else {
            // Going down
            $container.scrollTop(position + 10);
        }
    }, 100);
    div {
        border: 1px solid red;
        width: 200px;
        height: 200px;
        overflow: auto;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="divContainer">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>