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'); } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With