PacPac
PacPac

Reputation: 261

Make sidebar sticky on page scroll

I'm trying to make the sidebar of my page sticky on page scroll.

I've tried different solution but it doesn't work...

Here my last attempt:

$( document ).ready(function() {
  console.log( "document ready!" );

  var $sticky = $('.sticky');
  var $stickyrStopper = $('.sticky-stopper');
  if (!!$sticky.offset()) { // make sure ".sticky" element exists

    var generalSidebarHeight = $sticky.innerHeight();
    var stickyTop = $sticky.offset().top;
    var stickOffset = 0;
    var stickyStopperPosition = $stickyrStopper.offset().top;
    var stopPoint = stickyStopperPosition - generalSidebarHeight - stickOffset;
    var diff = stopPoint + stickOffset;

    $(window).scroll(function(){ // scroll event
      var windowTop = $(window).scrollTop(); // returns number

      if (stopPoint < windowTop) {
          $sticky.css({ position: 'absolute', top: diff });
      } else if (stickyTop < windowTop+stickOffset) {
          $sticky.css({ position: 'fixed', top: stickOffset });
      } else {
          $sticky.css({position: 'absolute', top: 'initial'});
      }
    });

  }
});

Here the source code of my page: https://codepen.io/anon/pen/bPareG

Can anyone of you help me please ?

Thanks a lot.

Upvotes: 0

Views: 354

Answers (1)

SaschaM78
SaschaM78

Reputation: 4497

As was also recommended in the comment by robinvrd, I would use position fixed as it avoids the hassle with calculating the new Y-position (better said, the browser takes care of this internally). So assuming you want your sticky box to scroll until it reaches the end of the view port and then remains visible on the side, this would be a solution:

$(window).scroll(function() {
  // scroll event
  var windowTop = $(window).scrollTop(); // returns number

  if (stickyTop < windowTop + stickOffset) {
    $sticky.css({ position: "fixed", top: 0, right: 0 });
  } else {
    $sticky.css({ position: "absolute", top: "initial", right: 0 });
  }
});

The changed code can be found in the mentioned Codepen.

Upvotes: 1

Related Questions