0

I would this code below to behave like below. 1. it will move to div1 when scrollTop is greater than 100 2. it will move to div2 when scrollTop is greater than div1.top position + 3. I can scroll back up and then it will behave the same for 1,2 when scrolling down.

currently it is stuck in div1. Can someone help figure this out?

$(window).scroll(function() {
  event.preventDefault();
  var div1 = $('#div1').offset();
  var div2 = $('#div2').offset();
  if ($(this).scrollTop() > 100) {
    //move to div1
    $('html, body').animate({
      scrollTop: div1.top
    },1000)
  }
  if ($(this).scrollTop() > div1.top + 100) {
    $('html, body').animate({
      scrollTop: div2.top
    },1000)
  }
});
jhlosin
  • 555
  • 1
  • 6
  • 17

2 Answers2

0

You can make use of $.stop() to stop the animation in progress to handle the scenario you are looking for :

    $(window).scroll(function() {
setTimeout(function() {
  var div1 = $('#div1').offset();
  var div2 = $('#div2').offset();
  var page = $("html, body");
  if ($(this).scrollTop() > 50) 
  {
    page.stop();
    page.animate({
      scrollTop: div1.top
    },500);
  }
  if ($(this).scrollTop() > div1.top + 100) 
  {
    page.stop();
    page.animate({
      scrollTop: div2.top
    },500)
  }
  },1000);
});

Example : https://jsfiddle.net/Lb1wj47j/3/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • Thank you, Dino. but your example does move it slowly for some reason and it does not seem to be doing what I want. – jhlosin Dec 29 '15 at 23:36
  • Since window.scroll event is invoked multiple times, you can wrap the logic inside a setTimeout. I've updated the solution and fiddle. Alternately, you can use https://github.com/yckart/jquery.unevent.js to unbind scroll event. – DinoMyte Dec 30 '15 at 01:02
0

Your code currently fires every time the user scrolls at all - you are catching the event and scrolling them back up before they can get past 100px to reach div2.

You need to throttle or debounce the handler - see these questions for implementation and details:

Community
  • 1
  • 1
brichins
  • 3,825
  • 2
  • 39
  • 60