HerrimanCoder
HerrimanCoder

Reputation: 7218

jquery fixed div while scrolling bounces around

I have a div (RightSide) on the far right side of my web page that sits just underneath another div (TopBanner). The TopBanner div maintains its exact position at the top of the screen even when user scrolls down. Exactly what I want. But I also want RightSide div (underneath TopBanner) to stay exactly where it is even when user scrolls down.

I have achieved this about 80% but it behaves strangely. When you begin to scroll down, RightSide begins to move up the page until it starts being obscured by TopBanner (goes behind it), and then suddenly it pops back down to its fixed position, and stays there for the remainder of scrolling. Here's the jquery that does the "popping back down":

var stickerTop = parseInt($('#RightSide').offset().top);
        $(window).scroll(function () {
            $("#RightSide").css((parseInt($(window).scrollTop()) + parseInt($("#RightSide").css('margin-top')) > stickerTop) ? {
                position: 'fixed',
                top: '0px'
            } : {
                position: 'relative'
            });
        });

It's the initial behavior of RightSide moving up the page for a hundred pixels or so before it pops back to its correct position that is driving my boss and our users crazy. I have experimented with changing "top: '0px'" to various values, but that only makes things worse.

It seems to me that the jquery that "re-anchors" RightSide doesn't get invoked until I've scrolled a hundred pixels or so, and then suddenly it moves the div down and keeps it in the right place after that.

Summary: I never want RightSide to move up or down, even while the user is dragging the vertical scrollbar (scrolling).

How can this be achieved? (I really don't want to use an iframe for this.) Thanks.

Upvotes: 0

Views: 1052

Answers (1)

szym_rutkowski
szym_rutkowski

Reputation: 24

How about packing these two divs into one with fixed position? Something like this?

<div id="StickToTop">
  <div id="TopBanner">
  ...
  </div>
  ...
  <div id="RightSide">
  ...
  </div>
</div>

And CSS:

#StickToTop {
  position: fixed;
  top: 0px;
}
#TopBanner {
  float: left;
  ...
}
#RightSide {
  float: right;
  ...
}

Quick preview: http://jsfiddle.net/k5xH4/3/

Upvotes: 1

Related Questions