2

I'm trying to make a div stick to the header once the user has started scrolling down the page . I found the example How can I make a div stick to the top of the screen once it's been scrolled to?

I used the code that has 24 votes . Live demo.

PROBLEMS : 1. I want to make the div stop before hitting the footer. i don't want to show it over the footer . 2. I don't know why this works with jquery 1.3.2 but not with 1.5.2 or a later version .

ofcourse any other jquery code / plugin or ideea would be great!

Community
  • 1
  • 1
mr.Liviu.V
  • 168
  • 3
  • 13

1 Answers1

4
$(window).load($(function()
{
    var elem = $("#scroller");
    var top = elem.offset().top;
    var maxTop = $("#footer").offset().top - elem.height();
    var scrollHandler = function()
    {
      var scrollTop = $(window).scrollTop();
      if (scrollTop<top) {
        elem.css({position:"relative",top:""})//should be "static" I think
      } else if (scrollTop>maxTop) {
        elem.css({position:"absolute",top:(maxTop+"px")})
      } else {
        elem.css({position:"fixed",top:"0px"})
      }
    }
    $(window).scroll(scrollHandler);scrollHandler()

}));

fiddle: http://fiddle.jshell.net/3ATzd/2/show/ Only think is it doesn't like the margin-top on #scroller. I also removed the need for the scroller-anchor element, so you can remove this.

Gerben
  • 16,747
  • 6
  • 37
  • 56
  • great job ! .. but you are right .. it does not like margin-top . and if we set a height of 600px to the scroller we would see that it will go over the footer .. but only 10px or so . http://fiddle.jshell.net/3ATzd/5/show/ – mr.Liviu.V Oct 19 '11 at 12:05
  • A dirty trick would be this : var maxTop = $("#footer").offset().top - elem.height() - 10; – mr.Liviu.V Oct 19 '11 at 12:07
  • also I found this : http://kitchen.net-perspective.com/open-source/scroll-follow/ But please feel free to share any other info and thanks a lot ! – mr.Liviu.V Oct 19 '11 at 12:08
  • You could just use padding-top. Or top:"0px" to top:"10px", and maxTop=... to maxTop=...-10 – Gerben Oct 19 '11 at 16:14