Reputation: 3903
I have an element which I only want to be position: fixed
until the end of a certain div. I was able make work somehow but still I can't the positioning work 100% smooth, so maybe you can help me out?
$(window).on("scroll", function() {
var scrollTop = $(this).scrollTop();
var containerOffset = $(".content").offset().top;
var containerHeight = $(".content").height();
var f1 = parseInt(containerHeight);
var f2 = parseInt(containerOffset);
var sum = f1 + f2;
if (scrollTop > sum - 240) {
$(".item")
.css("position", "relative")
.css("top", f1 + "px")
} else {
$(".item")
.css("position", "fixed")
.css("top", "20px");
}
});
.content {
height: 1000px;
border: 1px solid red;
background: grey;
}
.item {
position: fixed;
top: 20px;
height: 40px;
background: #fff;
width: 100%;
}
.another {
background: orange;
height: 400px;
}
.more {
background: darkblue;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content">
<div class="item">
scroll only until end of grey CONTENT DIV
</div>
</div>
<div class="another">
<h1>Another div</h1>
</div>
<div class="more">
<h1>More content</h1>
</div>
</div>
Upvotes: 0
Views: 1557
Reputation:
Add this css to your html
div.sticky_top {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 20px;
}
and add sticky_top
class to your item div - no need for javascript or jquery
<div class="item sticky_top">
scroll only until end of grey CONTENT DIV
</div>
https://codepen.io/anon/pen/bxZaPd
Upvotes: 1
Reputation: 28611
You can tweak when it starts to scroll by adjusting
if (scrollTop > sum - 240) {
it's not clear where 240 came from, but match this with your .item
top
attribute to give
if (scrollTop > sum - 20) {
and it gives what (it looks like) you're after
$(window).on("scroll", function() {
var scrollTop = $(this).scrollTop();
var containerOffset = $(".content").offset().top;
var containerHeight = $(".content").height();
var f1 = parseInt(containerHeight);
var f2 = parseInt(containerOffset);
var sum = f1 + f2;
if (scrollTop > sum - 20) {
$(".item")
.css("position", "relative")
.css("top", f1 + "px")
} else {
$(".item")
.css("position", "fixed")
.css("top", "20px");
}
});
.content {
height: 1000px;
border: 1px solid red;
background: grey;
}
.item {
position: fixed;
top: 20px;
height: 40px;
background: #fff;
width: 100%;
}
.another {
background: orange;
height: 400px;
}
.more {
background: darkblue;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content">
<div class="item">
scroll only until end of grey CONTENT DIV
</div>
</div>
<div class="another">
<h1>Another div</h1>
</div>
<div class="more">
<h1>More content</h1>
</div>
</div>
Updated fiddle: https://jsfiddle.net/pb0Ljtn4/20/
Upvotes: 0