Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll in 100% steps inside div

I have a div that contains several children with 100% height. On scrolling I always want to go down or up exactly the height of one child, so 100%. Unfortunately I can't figure out how to prevent scrolling multiple steps at a time. I tried event.preventDefault() and also using timeouts, but none worked yet.

Check out the fiddle to see what I've got so far - and what the issue look like exactly.

$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>
like image 897
Thomas Avatar asked Jun 23 '26 15:06

Thomas


1 Answers

Actually there are three issues in your code, which creates the confusion:

  1. The scroll event cannot be cancelled.
  2. $.animate the scrollTop will trigger a scroll event right after the complete function has run.
  3. All animations will be queued an executed, not matter what value doScroll has.

The biggest problem here is the additional scroll event triggered by the animation. To overcome this, you have to carefully manage the event handling, e.g. by skipping over the event triggered by the animation.

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

like image 89
mrgrain Avatar answered Jun 26 '26 05:06

mrgrain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!