Sticky sidebar is an essential part of web development. Not in all cases but for some cases where our page has more content in one side and so we need to fix the other side on scroll of the page.

Javascript css sticky sidebar is the important part of web development

The Jquery part

<script>
$(document).ready(function() {
function isScrolledTo(elem) {
var docViewTop = $(window).scrollTop(); //num of pixels hidden above current screen
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top; //num of pixels above the elem
var elemBottom = elemTop + $(elem).height();

return ((elemTop <= docViewTop));
}

var catcher = $('#catcher');
var sticky = $('#sticky');

$(window).scroll(function() {
if(isScrolledTo(sticky)) {
sticky.css('position','fixed');
sticky.css('top','0px');
}
var stopHeight = catcher.offset().top + catcher.height();
if ( stopHeight > sticky.offset().top) {
sticky.css('position','absolute');
sticky.css('top',stopHeight);
}
});
});
</script>


<div id="content">

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

What is Demo text?

Demo

Text

</div>
<div id="sidebar">

<div id="sticky">

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

</div>
</div>

Leave comment

Your email address will not be published. Required fields are marked with *.