simonrl simonrl -4 years ago 46
Javascript Question

How to cancel a javascript function if the user scrolls the page

Using this javascript to scroll to a div (#Content) after a 5s delay using setTimeout.

setTimeout(function () {
$('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
}, 5000);


How would I go about cancelling this action if the user scrolls manually before the 5s is elapsed. Reason being if the user has scrolled they'll be annoyed if the page then auto scrolls.

Tried putting it in window.load and checking for if ($(window).scrollTop() == 0) but of course that's always true at window.load, and isn't cancelled by the user scrolling manually.

Thanks!

Answer Source

you can use for example global variable and check if its set up by event scroll

var scrolled = false;
$(document).scroll(function(){scrolled = true;});
setTimeout(function () { 
 if (!scrolled){
    $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 
    1000); }
  }
}, 5000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download