Fixed div on scroll when its reach top of window
Fixed div on scroll when its reach top of window
by AlexKhrapal
HTML
<h2>Scroll To Bottom</h2>
<br>
<br>
<br>
<br><br>
<div id="the-sticky-div">it will fix on top when touch top of the window</div>
CSS
body{
height:2000px; /* added height for testing pupose only */
}
#the-sticky-div{
/* these styles not mandotary */
width:100%;
color:#fff;
height:50px;
background:#333;
left:0;
text-align:center
}
#the-sticky-div.sticky {
position: fixed; /* mandotary*/
top: 0;/* You can change the top as per your wish */
}
</style>
JavaScript
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});