Skip to content Skip to sidebar Skip to footer

$('body, Html').is(':animated')) Doesn't Seem To Be Working

I have 4 divs with heights set to window height. I want on each scroll down to scroll to the next one, however after the first scroll down it just keeps on scrolling, seemingly ign

Solution 1:

I guess this is what you're going for: https://jsfiddle.net/2d47k6af/5/

The problem was that you can't distinguish scroll events triggered by JavaScript and by user themself. So when you run the animation it fired many $(window).on("scroll", ...); events that were ignored thanks to $('body, html').is(':animated') that worked as expected.

However the last scroll event occured probably after the animation has ended so function scrollSections() was called one more time which triggered another animation and so on. My solution would be to add a short timeout after the animation has ended and before it's ready to another user triggered scroll:

$('body, html').animate({scrollTop: pos}, 1000, function() {
  console.log('animated');
  ignoreScrollEvents = true;

  setTimeout(function() {
    ignoreScrollEvents = false;
  }, 100);

});

Solution 2:

You can to use variable to achieve, what you want:

function setHeights() {
  $('.nbhd').css('height', window.innerHeight);
}


var isAnimated = false; // Initialize variable
function scrollSections() {
  if (isAnimated) return; // Previous animation still in action
  isAnimated = true; // lock it
  var currentSectionId = $('.nbhd.scrolledto').data('id');

  currentSectionId++;
  var section = $('#id'+currentSectionId);
  if (!section.length) {
    currentSectionId = 0;
    section = $('#id0');
  }

  $('.scrolledto').removeClass('scrolledto');

  section.addClass('scrolledto');

  var pos = section.offset().top;

  $('body').animate({scrollTop: pos}, 1000, function() {
      setTimeout(function(){
        isAnimated = false; // unlock it on next eventloop tick
      })
  });
}

setHeights();



$( window ).on( "scroll", function() {
    scrollSections();
});
.div {width: 100%;}
.red {background: red;}
.yellow {background: yellow;}
.green {background: green;}
.blue {background: blue;}
<div id="id0" data-id="0" class="nbhd red scrolledto"></div>
<div id="id1" data-id="1" class="nbhd yellow"></div>
<div id="id2" data-id="2" class="nbhd green"></div>
<div id="id3" data-id="3" class="nbhd blue"></div>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Post a Comment for "$('body, Html').is(':animated')) Doesn't Seem To Be Working"