Check out this CodePen example. Go to the tab block by scrolling down. When you scroll to the top, it adds the 'sticked' class, and when it reaches the bottom of the parent element, it gets the 'sticked2' class. The problem arises when you set top: 1px
or more with the 'sticked' class, causing a bug (?) that stops the script from working correctly. Why does this happen?
var $window = $(window);
$window.scroll(function() {
var labels = $('.forlabels'),
labelsSec = $('.forlabels-section'),
bottomOfLabels = labels.outerHeight() + labels.offset().top,
bottomOfLabelsSec = labelsSec.outerHeight() + labelsSec.offset().top,
topOfLabels = labels.offset().top,
topOfLabelsSec = labelsSec.offset().top,
isAboveTopSec = $window.scrollTop() < topOfLabelsSec,
isAboveTop = $window.scrollTop() < topOfLabels,
isBelowTop = $window.scrollTop() >= topOfLabels,
isBelowBottom = bottomOfLabelsSec <= bottomOfLabels;
if (!isAboveTopSec && ((isBelowTop && !isBelowBottom) || isAboveTop)) {
$('.forlabels')
.addClass('sticked')
.removeClass("sticked2")
.text("Sticked");
} else if (isBelowBottom) {
$('.forlabels')
.addClass('sticked2')
.removeClass('sticked')
.text("Scrolled Below Bottom");
} else {
$('.forlabels')
.removeClass('sticked sticked2')
.text("Not sticked ");
}
});
* {
box-sizing: border-box;
}
.one-half {
position: relative;
padding: 0 10px;
}
.one-half {
-webkit-box-flex: 1;
-ms-flex: 1 45%;
flex: 1 45%;
-webkit-flex: 1 45%;
min-width: 300px;
border: 1px solid red;
height: 100%;
}
.fbox {
height: 1800px;
margin-top: 100px;
border: 1px solid #000;
display: flex;
align-items: flex-start;
}
.forlabels-section {
height: 500px;
background: green;
position: relative;
}
.forlabels {
height: 100px;
background: #777;
}
.forlabels,
.forlabels-section {
width: 200px;
}
.sticked {
position: fixed;
top: 0;
bottom: inherit;
}
.sticked2 {
bottom: 0px;
position: absolute;
top: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fbox">
<div class="forlabels-section">
<div class="forlabels">Untouched Column</div>
</div>
<div class="one-half columned">
</div>
</div>