0

I'm trying to toggle a div from relative to fixed when I scroll down 200px using javascript. When I reach 200px from the top of the window, my div should toggle to fixed. And when I'm above that 200px from the top it should go back to relative. Does anyone have an idea on how to do this?

BeDesinged
  • 55
  • 1
  • 3
  • 8

2 Answers2

2

Something like:

$(window).on('scroll', function() {
    $("#myDivID").css({
       position: $(this).scrollTop()<200?'relative':'fixed',
       top: $(this).scrollTop()<200?'200px':'0px'
    });
});

You'll probably also have to reset the top position of the element.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Wow, that was fast. Thanks! How would I go about "resetting the the top"? – BeDesinged Aug 28 '12 at 15:54
  • I would suggest to previously cache a reference to `$("#myDivID")`, otherwise you will re-evaluate that every time the scroll event occurs, e.g. You could declare it in the upper scope, wrapping all code in an anonymous immediate executed function – Fabrizio Calderan Aug 28 '12 at 15:58
  • Well, if your element has css top set to `200px` and you scroll down until the element is all the way at the top of the screen, and then suddenly you change to position `fixed`, you'll see that the element jumps down to 200px from the top, as now it's no longer in the document flow. In such cases you'll have to alse change the top position to zero, but what the exact numbers are depends on your design. – adeneo Aug 28 '12 at 15:58
  • @FabrizioCalderan - It sets the elements style property on every scroll, there's no need to cache the selector for this ! – adeneo Aug 28 '12 at 15:59
0

I know there's at least a couple of plugins that do this. Can't remember the name of the one I saw last, but here's one I've written myself: http://code.google.com/p/sleekphp/source/browse/trunk/Sites/SleekBase/Modules/Base/JS/jQuery.fixedIfNeeded.js

You use it like so:

$('#my-element').fixedIfNeeded();

There's one optional argument that specifies if the element should stop being fixed before it reaches another element (like a footer for example):

$('#my-element').fixedIfNeeded('#footer');
powerbuoy
  • 12,460
  • 7
  • 48
  • 78