How to Implement Automatic Scrolling with jQuery

Automatic scrolling is a feature that causes a web page to scroll down automatically at a predetermined and configurable rate. This is quite a useful feature for websites that contain long articles, posts or some other lengthy web content. This feature saves users from having to scroll the page using their mouse or keyboard. In this post, let’s look at a few ways to implement automatic scrolling for any website using jQuery.

HTML Markup

First of all, we want this feature to be easily configurable so that the user has the option to…

  • start and stop automatic scrolling
  • set the rate
  • set how much pixel the screen should scroll automatically.

Therefore, we need 2 input boxes to get time and pixel value:

Time (in Seconds) :

<input type="text" id="txtTime" value="3" />

Pixel :

<input type="text" id="txtPixel" Value="100"/>

By default, the time is set to 3 seconds and the pixel value is set to 100 pixels.

We also need 2 HTML buttons to start and stop scrolling:

<input type="button" id="btnStart" value="Start Scrolling" />
<input type="button" id="btnStop" value="Stop Scrolling" />

Finally, we will also require another button that will become visible only when ‘stop scrolling’ is clicked:

<input type="button" id="btnStartHidden" style="display:none;" value="Start Scrolling" />

By default, this button will be hidden. When ‘stop scrolling’ is selected this button becomes visible in the top-left section of the page. This is necessary so that when the user wants to start scrolling again they can easily do so by clicking here. The stop scrolling button scrolls along with the content of the webpage so that the user can stop scrolling at any time without backtracking to the top of the page.

The HTML will look like this:

Screen Shot 2017-03-08 at 3.56.33 PM

CSS

The following CSS classes are used to style and position the elements present on the HTML page. These CSS classes both style the buttons and set their positions. There is also a CSS class defined for the hidden button to position it at the top left of the page:

input[type="text"] { 
    width:50px; 
}
#btnStop {
    position: absolute;
    right: 0px;
    top: 0px;
    background-color: red;
}
#btnStartHidden {
    position: absolute;
    left: 0px;
    top: 0px;
}
.button {
    background-color: #4CAF50; /* Green */   
    border: none;
    color: white;
    padding: 10px 12px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

jQuery Code

To implement this functionality, we will need to use JavaScript setInterval() and clearInterval().The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.  The clearInterval() method clears a timer set with the setInterval() method.

The following is the outline of the jQuery solution:

  • Define the global variable as scrollInterval. This will be responsible for handling the setInterval() and clearInterval() timer.
  • Retrieve the time value now as it will be used in different parts of the code so better to fetch it once and store it in a global variable. Since setInterval takes the timer value in milliseconds, you’ll want to multiply the seconds by 1000 to get the millisecond value:
var scrollInterval = false;
var iSeconds = $('#txtTime').val();
iSeconds = parseInt(iSeconds) * 1000;
  • Create a function named AutomaticScroll. This will scroll the page and set the position of the ‘Stop Scrolling’ button to inline with the page scroll position. This function also reads the input value of pixels and use time defined in a global variable to get the correct scroll position based on user preference. It is also responsible for stopping the scroll once the end of the page is reached. If we don’t set the scrolling function to stop the setInterval will keep on calling this function, which is not required.
function AutomaticScroll() {   
    var nScrollTop = $(window).scrollTop();   
    if (parseInt(nScrollTop + $(window).height()) == $(document).height()) {
        clearInterval(scrollInterval);
        return;
    }   
    var nPixel = $('#txtPixel').val();
    nScrollTop = nScrollTop + parseInt(nPixel);
    $('html, body').animate({
        scrollTop: nScrollTop
    }, 1000);
    $('#btnStop').animate({
        "top": nScrollTop + "px"
    }, 1500); 
}
  • On click of Start Scrolling button, make a call to the AutomaticScroll function using setInterval(). Here the scrollInterval variable holds the reference of setInterval(). So if we wish to stop the scrolling, we pass this reference to the clearInterval() function:
$('#btnStart').click(function() {
    scrollInterval = setInterval(AutomaticScroll, iSeconds); 
});
  • On click of Stop Scrolling button, the reference of the setInterval() variable is cleared using clearInterval(). At this point the hidden button will also appear so that the user can begin scrolling again at any time. The hidden button will be visible on the top left corner of the page. Like this:
$('#btnStop').click(function() {
    clearInterval(scrollInterval);
    var nScrollTop = $(window).scrollTop();
    if (nScrollTop != 0) {
        $('#btnStartHidden').show(500);
        $('#btnStartHidden').animate({
            "top": nScrollTop + "px"
        }, 500);
    } 
});
  • When the hidden button is selected, we again call the AutomaticScroll function with setInterval to start scrolling again. At this point we also hide this button again with some animation:
$('#btnStartHidden').click(function() {
    scrollInterval = setInterval(AutomaticScroll, iSeconds);
    $(this).hide(1000); 
});
  • We also need to handle the positioning of the stop scrolling button when scrolling is stopped by the user and the user moves to the top of the page using the browser’s scrollbar. Since the stop scrolling button’s position is absolute, we need to move it to the top of the page as well. So, attach a scroll event to the window object and check for the scroll position using scrollTop. ScrollTop reads the current vertical position of the scroll bar for the first element in the set of matched elements or sets the vertical position of the scroll bar for every matched element.

As an example, scrollTop value 0 would be the top of the page. So we hide the hidden button and also set the position of the ‘stop scrolling’ button so that it is shown in the top right corner, like this:

$(window).scroll(function() {
    var nScrollTop = $(window).scrollTop();
    if (parseInt(nScrollTop) == 0) {
        $('#btnStartHidden').hide();
        $('#btnStop').animate({
            "top": nScrollTop + "px"
        }, 1500);
    } 
});

Finally, here is the complete jQuery code:

$(document).ready(function() { 
    var scrollInterval = false; 
    var iSeconds = $('#txtTime').val(); 
    iSeconds = parseInt(iSeconds) * 1000; 
    function AutomaticScroll() {   
        var nScrollTop = $(window).scrollTop();   
        if (parseInt(nScrollTop + $(window).height()) == $(document).height()) {
            clearInterval(scrollInterval);
            return;
        }   
        var nPixel = $('#txtPixel').val();
        nScrollTop = nScrollTop + parseInt(nPixel);
        $('html, body').animate({
            scrollTop: nScrollTop
        }, 1000);
        $('#btnStop').animate({
            "top": nScrollTop + "px"
        }, 1500); 
    } 
    $(window).scroll(function() {
        var nScrollTop = $(window).scrollTop();
        if (parseInt(nScrollTop) == 0) {
            $('#btnStartHidden').hide();
            $('#btnStop').animate({
                "top": nScrollTop + "px"
            }, 1500);
        } 
    }); 
    $('#btnStart').click(function() {
        scrollInterval = setInterval(AutomaticScroll, iSeconds); 
    }); 
    $('#btnStartHidden').click(function() {
        scrollInterval = setInterval(AutomaticScroll, iSeconds);
        $(this).hide(1000); 
    }); 
    $('#btnStop').click(function() {
        clearInterval(scrollInterval);
        var nScrollTop = $(window).scrollTop();
        if (nScrollTop != 0) {
            $('#btnStartHidden').show(500);
            $('#btnStartHidden').animate({
                "top": nScrollTop + "px"
            }, 500);
        } 
    });
});

You can also check the demo at following link!

Conclusion

To sum it up, we saw how to implement the automatic scrolling functionality based on user defined time and pixel value. The solution also gives the flexibility to the user to stop the scrolling at any point, and then start it again if they wish. This functionality is useful for lengthy articles and it will save user’s time in scrolling the page.



Responsive Menu
Add more content here...