Reputation: 345
Would like to trigger the same function on $(window).resize and on $("#foo").scroll.
Need #stick
to stick to the top of #foo
. The problem is that the position of #stick
gets a bit jumpy when scrolling and when resizing the window. Any help?
Upvotes: 0
Views: 394
Reputation: 97631
First, we add two more containers - a .content
div inside #foo
, and an .inner
div inside #stick
:
<div id="foo">
<div class="content">
<p>Lorem ipsum dolor sit amet.</p>
<div id="stick">
<div class="inner">stick</div>
</div>
<p>...</p>
</div>
</div>
Note that #anchor
is gone.
The css for the container gets split in half:
#foo {
position: relative;
margin: 50px auto;
width: 200px;
height: 200px;
}
#foo .content {
width: inherit;
height: inherit;
overflow: auto;
}
And we apply the following to the #stick
. The inner box inherits its size from the outer one.
#stick {
width: 100px;
height: 50px;
}
#stick .inner {
width: inherit;
height: inherit;
background: pink;
}
#stick.stuck .inner {
position: absolute;
top: 0;
}
Almost everything is take care of in css - the javascript is:
$(document).ready(function() {
$("#foo .content").scroll(stickyTop);
$(window).resize(stickyTop);
});
function stickyTop() {
//position is now relative to #foo
if ($("#stick").position().top < 0)
$("#stick").addClass('stuck');
else
$('#stick').removeClass('stuck');
}
Upvotes: 2