You can find an example below. Basically you attach a function to window
‘s scroll
event and trace scrollTop
property and if it’s higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {
$(window).scroll(function fix_element() {
$('#target').css(
$(window).scrollTop() > 100
? { 'position': 'fixed', 'top': '10px' }
: { 'position': 'relative', 'top': 'auto' }
);
return fix_element;
}());
});
body {
height: 2000px;
padding-top: 100px;
}
code {
padding: 5px;
background: #efefef;
}
#target {
color: #c00;
font: 15px arial;
padding: 10px;
margin: 10px;
border: 1px solid #c00;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="target">This <code>div</code> is going to be fixed</div>