How to fix div on scroll [closed]
If you scroll down the page in the following URL, the 'share' div will lock onto the browser:
http://knowyourmeme.com/memes/pizza-is-a-vegetable
I'm assuming they are applying a position: fixed;
attribute. How can this be achieved with jQuery?
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>
On jQuery for designers there's a well written post about this, this is the jQuery snippet that does the magic. just replace #comment with the selector of the div that you want to float.
Note: To see the whole article go here: http://jqueryfordesigners.com/fixed-floating-elements/
$(document).ready(function () {
var $obj = $('#comment');
var top = $obj.offset().top - parseFloat($obj.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$obj.addClass('fixed');
} else {
// otherwise remove it
$obj.removeClass('fixed');
}
});
});
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
fiddle http://jsfiddle.net/wq2Ej/
jquery
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
css:
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}