Search code examples
jquerycsspositionjquery-waypoints

Prevent flash/bounce of content when transitioning to position: fixed


I use the jQuery Waypoints library to modify the position of a menu bar container from static to fixed. When the browser window is scrolled down to the menu bar, the bar is fixed to the top of the window.

When scrolling slowly to/past the waypoint, the state change appears to happen smoothly, but when I scroll with normal speed, a slight jump/bounce happens to the menu bar content.

Markup:

<div class="wrapper">
  <div class="less"></div>
  <div class="container">
    <nav>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Clients</a></li>
        <li><a href="#">Contact Us</a></li>
      </ul>
    </nav>
  </div>
  <div class="more"></div>
</div>​

Relevant CSS:

.container {
  height: 50px;
}
nav {
  background: #cdce12;
  height: 50px;
}
nav ul {
  margin: 0;
  padding: 0;
}
nav li {
  display: inline-block;
}
.sticky nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

Here's the jQuery code:

$(function() {
  var $container = $('.container');
  var $b = $('body');
  $container.waypoint({
    handler: function(event, direction) {
      $b.toggleClass('sticky', direction === 'down');
      event.preventDefault();
    }
 });
});​

I've set up a JSFiddle to illustrate the problem and I wonder if it's possible to prevent this effect to happen?


Solution

  • You can make it better by setting the scroll throttle to 0, however there is still a tiny bounce.

    $.waypoints.settings.scrollThrottle = 0;
    

    http://jsfiddle.net/FHvha/3/