By setting the parent of #mini-mini2
to have position:relative
, you can position #mini-mini2
absolutely within it. Then, your JavaScript can set the element's position top
to be the current scrollTop
minus the header height, ensuring that #mini-mini2
does not get pushed too far.
To see this concept in action, check out the example below:
$(document).ready(function() {
var breaking = $('.big-one').offset().top;
var limit = $('.my-footer').offset().top - $('#mini-mini2').height();
$(window).scroll(function() {
var scrolltop = $(window).scrollTop();
var top = scrolltop - breaking;
if (scrolltop > breaking && scrolltop < limit) {
$('#mini-mini2').css("top", top);
}
});
});
.my-top,
.my-footer {
width: 100%;
height: 50px;
border: 1px solid;
}
.my-top {
height: 250px;
}
.my-footer {
height: 450px;
}
/* Additional CSS styles */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-top">
<p>
This is my top
</p>
</div>
<div class="big-one">
<div class="mini1">
<p>
TEST 1
</p>
</div>
<div class="mini2">
<div id="mini-mini2">
<p>
Need to scroll
</p>
</div>
</div>
</div>
<div class="my-footer">
<p>
This is my footer
</p>
</div>
View the updated jsFiddle for further reference: Updated jsFiddle
UPDATE
A more precise approach involves toggling the elements between position:fixed
and adjusting top
vs bottom
positions in order to prevent misalignment of #mini-mini2
when scrolling too quickly. Check out the updated code snippet below:
$(document).ready(function() {
var breaking = $('.big-one').offset().top;
var limit = $('.my-footer').offset().top - $('#mini-mini2').height();
$('#mini-mini2').css("width",$('.mini2').width());
$(window).resize(function() {
$('#mini-mini2').css("width",$('.mini2').width());
});
$(window).scroll(function() {
var scrolltop = $(window).scrollTop();
var top = scrolltop - breaking;
if (scrolltop > breaking && scrolltop < limit) {
$('#mini-mini2').addClass("fixed");
$('#mini-mini2').css("bottom", "auto");
$('#mini-mini2').css("top", 0);
} else if(scrolltop > breaking) {
$('#mini-mini2').removeClass("fixed");
$('#mini-mini2').css("bottom", 0);
$('#mini-mini2').css("top", "auto");
} else {
$('#mini-mini2').removeClass("fixed");
$('#mini-mini2').css("bottom", "auto");
$('#mini-mini2').css("top", 0);
}
});
});
.my-top,
.my-footer {
/* Styles for .my-top and .my-footer */
}
/* Additional CSS styles */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-top">
<p>
This is my top
</p>
</div>
<div class="big-one">
<div class="mini1">
<p>
TEST 1
</p>
</div>
<div class="mini2">
<div id="mini-mini2">
<p>
Need to scroll
</p>
</div>
</div>
</div>
<div class="my-footer">
<p>
This is my footer
</p>
</div>
For the latest version, visit: Updated jsFiddle