How to automatically go to top after x seconds if user scrolled down

Issue

I’m new. New to JS/CSS and Stack Overflow.

I have a div box with the CSS property overflow: auto.
If a user scrolls down in the DIV box, it should automatically scroll to the top again after x seconds.

Is this possible? And how is this possible?

I think it should detect if the scrollbar is not in the start position to let the countdown count.
After x seconds it should go back to top. Right?

Thank you.

Solution

try this with setTimeOut() function and page idle

  
 $(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       setTimeout(function(){ 
        $('html,body').animate({
            scrollTop: 0
        }, 700);
       }, 5000);
   }
});

var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every second.
    var idleInterval = setInterval(timerIncrement, 1000); // 1 second

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 10) { // 10 seconds
        idleTime = 0;
        $('html,body').animate({
            scrollTop: 0
        }, 700);
    }
}
#content {
    height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">Scroll &darr;</div>

Answered By – Udhay Titus

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published