Thomas
Thomas

Reputation: 4297

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>

Upvotes: 3

Views: 1763

Answers (2)

mrgrain
mrgrain

Reputation: 441

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.

Upvotes: 2

dipole_moment
dipole_moment

Reputation: 5854

Personally, I would use location hashes #.

If you place anchors within your divs which contain href="#child1" for example then you would be able to scroll to them with javascript by doing location.hash="#child1".

For animated scrolling to location hashes, check out this script

Upvotes: 2

Related Questions