How can I run jQuery function only if user hasn’t scrolled?

145 Views Asked by At

I’ve been trying to incorporate an auto scroll function on my website (live here). I want it to scroll to the content 6 seconds after load, but only if the user is on the very top of the page and hasn’t scrolled enough to uncover the #introduction element.

I have this code, which works, but I don’t want it to execute if the user has already scrolled by themself:

$('html,body').delay(6000).animate({
    scrollTop: $('#introduction').offset().top
}, 1000);

I would also like it to happen with a type of ease-in-out, if possible.

1

There are 1 best solutions below

3
bas On BEST ANSWER

You can do something like this:

$('html')
  .delay(6000)
  // If the user has scrolled down, do nothing. Otherwise scroll to element
  .queue(function(next) {
    if ($(window).scrollTop() > 0) {
      return;
    } else {
      next();
    }
  })
  .animate(
    {
      scrollTop: $('#introduction').offset().top,
    },
    1000,
    'swing',
  );

As for the ease-in-out animation you need JqueryUI for that. swing and linear are the Jquery library supported easing functions.