Loop 100% steps inside a div

I have a div that contains multiple children with 100% height. When scrolling, I always want to go down or go up exactly one child's height, so 100%. Unfortunately I cannot figure out how to prevent scrolling multiple steps at a time. I tried event.preventDefault()

as well with timeouts but didn't work so far.

Review the fiddle to see what I have so far and what the problem looks like.

$container = $('#container');
var doScroll = true;
var top = 0;

$container.on("scroll", function(event){
    event.preventDefault();
    if (doScroll) {
        doScroll = false;
        top += $container.height();
        console.log("scroll event fired");
        $container.animate({scrollTop: top}, '700', 'swing', function() { 
            doScroll = true;
        });
    } 
});

      

#container {
  height: 500px;
  width: 300px;
  overflow-y: auto;
  overflow-x: hidden;
}
.child {
  height: 100%;
  width: 100%;
}
.red {
  background-color: red;
}
.blue {
  background-color: blue;
}

      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
  <div class="child red">Child 1</div>
  <div class="child blue">Child 2</div>
  <div class="child red">Child 3</div>
  <div class="child blue">Child 4</div>
  <div class="child red">Child 5</div>
</div>

      

+3


source to share


2 answers


There are actually three problems in your code that create confusion:

  • The event scroll

    cannot be canceled .
  • $.animate

    scrollTop

    fires an event scroll

    immediately after the full function is executed.
  • All animations will be queued, no matter what the value is doScroll

    .


The biggest problem here is the additional event scroll

triggered by the animation. To overcome this, you must carefully manage your event handling, for example. skipping the event triggered by the animation.

For an example, see a working demo that also clears the animation queue after each run.

+2


source


Personally, I would use location hashes #

.

If you place anchors inside your divs that contain href="#child1"

, for example, you can loop through them with javascript by doing location.hash="#child1"

.



For animated scrolling to hashes of locations check this script

+2


source







All Articles