DavideR
DavideR

Reputation: 570

Fixed div inside other div after certain scroll

I have a div inside another div like this:

<div class="parent">
<div class="child">Text</div>
</div>

I want, with jQuery, to make child fixed as long as it stays inside his parent.. I've tried something like this:

$(document).scroll(function() {
var y = $(document).scrollTop();

if(y >= $(".child").offset().top)  {
        $(".child").css("position", "fixed");
    } else {
        $(".child").css("position", "relative");
    }
});

But it (obviously) just makes it fixed. I want to make it fixed until it "hits" the bottom border of his parent. What should I do?

EDIT: Fiddle: http://jsfiddle.net/8T7Hr/

Upvotes: 0

Views: 1031

Answers (1)

Batu.Khan
Batu.Khan

Reputation: 3065

var parent_top = $(".parent").offset().top;
var parent_bottom = $(".parent").offset().top + $(".parent").height() - $(".child").height();

$(document).scroll(function() {
  var y = $(document).scrollTop();

  if(y >= parent_top && y <= parent_bottom)  {
    $(".child").css({"position": "fixed", "top" : "0px"});
  } else {
    $(".child").css("position", "relative");
  }
});

FIDDLE

Upvotes: 3

Related Questions