简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM