Matt
Matt

Reputation: 22911

Add boundaries to element with position:fixed

I've got a div with position: fixed that moves with the scroll properly, but I'd like to have it stop when it reaches certain (y-axis) boundaries. What's the method to go about doing this?

Ideally the solution doesn't flicker and is performant. Twitter's right panel is close to what I'd like.

Upvotes: 0

Views: 2013

Answers (1)

CarpeNoctumDC
CarpeNoctumDC

Reputation: 1760

This is a more functional vetrsion of http://jsbin.com/ijexe (updated the code to reenable the origional position... essentially once it hits its origional top position it will start scrolling again)

You can update the http://jsbin.com/ijexe code to test simply by swapping out the jquery function with the one below...

In the

<script type="text/javascript" src="Sandbox_files/jquery.min.js"></script>

in the example:

.fixedElement {
    Z-INDEX: 100; POSITION: absolute; BACKGROUND-COLOR: #c0c0c0; WIDTH: 100%; HEIGHT: 30px; COLOR: #800000; FONT-SIZE: large; TOP: 200px
}

(just make sure you have your position:absolute & top: value set)

Updated function (place before the closing body tag)

<script type="text/javascript">
$(window).scroll(function(e){

  var scrollTo = 200;
  var scrollClass = '.fixedElement';

  $el = $(scrollClass);
  position = $el.position();
  if ($(this).scrollTop() > scrollTo && $el.css('position') != 'fixed'){
    $(scrollClass).css({'position': 'fixed', 'top': '0px'});
  } else if ((position.top < scrollTo) && ($el.css('position') != 'relative')){
     $(scrollClass).css({'position': 'relative', 'top': '200px'});
  }
});
</SCRIPT>

You can update: scrollTo - The offset from the top of the screen to start/stop the element scrolling

* Just make sure scroll to is set to the same value as your stylesheet decliration...

scrollClass - The class name for the element(s) to apply the function to

Upvotes: 1

Related Questions