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

Viewed 536

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.

3 Answers

Here's a non jQuery version:

var timeout;

function returnToTop() {
    if (!timeout) {
        timeout = setTimeout(() => {
            document.getElementById("scrollable").scroll(0, 0);
            timeout = null;
        }, 5000)
    }
}
#scrollable {
  height: 200px;
  overflow-y: scroll;
}

#interior {
  height: 500px;
}
<div id="scrollable" onscroll="returnToTop()">
  <div id="interior">
    scroll me!
  </div>
</div>

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>

Adjust the time in the setTimeout function.

var scrolltimer = null;
window.addEventListener('scroll', function() {
    if(scrolltimer !== null) {
        clearTimeout(timer);        
    }
    scrolltimer = setTimeout(function() {
          // do something
    }, 150);
}, false);
Related