1

I am trying to achieve an effect similar to what this page shows: When the top of the window reaches the top of a particular container, I want it to get sticked in the top of the window.

I have found this question in SO which deals with this behaviour. But I am not looking the container to get stick when the user reaches a particular px, but when the user reaches the start of a container. I want it this way because the size between the top of the page and the top of the container can vary.

My questions are:

-> How can I know when I have reached the top of a particular container.
-> If that container has the position: relative, because it has several elements inside which are relatively positioned, and therefore I can't use fixed, what would I do?
-> How can I reset the container once I scroll up and I reach the same point where it was positioned?

Thanks

Community
  • 1
  • 1
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296
  • You can use fixed. "[an] absolutely positioned element is positioned relative to _nearest positioned ancestor_." https://developer.mozilla.org/en-US/docs/CSS/position ; http://jsfiddle.net/honnza/3nD8t/ – John Dvorak Jan 31 '13 at 11:37

1 Answers1

0

Use this:

 $(window).scroll(function(e){
 $el = $('.class_of_fixedElement or #id_of_fixedelement');
 if ($(this).scrollTop() > 200 && $el.css('position') != 'fixed'){
 $('.fixedElement').css({'position': 'fixed', 'top': '0px'});
 }
 });

replace 200 with whatever pixels you want.as soon as scrolltop reaches there,your element get fixed to top.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • But how do I know where the top of my container is in the loading of the page? I don't know it because the distance between the top and the top of the page can vary. – Hommer Smith Jan 31 '13 at 11:41
  • 2
    @HommerSmith try `.offset().top` – John Dvorak Jan 31 '13 at 11:41
  • Thanks for the answer. I am wondering two things though, and I have edited my question. Once I scroll up, I would need to put the container back again where it was. How could I do this? – Hommer Smith Jan 31 '13 at 13:40
  • @HommerSmith:you need to write else part where you change its position to relative and top to original value. – Milind Anantwar Jan 31 '13 at 13:45