Picture of How to Make Sidebar Sticky Using CSS & jQuery?

How to Make Sidebar Sticky Using CSS & jQuery?

Making page content that sticks to the viewport as you scroll, something like a jump-to-anchor menu or section headings, has never been easier. However, sticky positioning can get tricky, especially when it comes to height and the dangerous situation of hiding content in a position that can’t be scrolled to. Let me show you how we can make the sidebar sticky.

<div class="after-header">
	<div class="container">
		<div class="main"> </div>
		<div class="sticky-form">
			<div class="sticky-form-inner"> </div>
		</div>
	</div>
</div>

We created <div class="after-header"> to wrap the center part and then we’ll use that to calculate the height of the content. Place the following code to your style.css.

.after-header {
	position: relative;
}

.sticky-form {
	right: 0;
}

.sticky-form-inner {
	position: sticky;
	top: 124px;
}

And the final part where we are going to add some magic!

height = jQuery('.after-header').height();
if(jQuery(window).width() >= 768) {
	jQuery('.sticky-form').css({
		'height': height - 100,
		'position': 'absolute'
	});
} else {
	jQuery('.sticky-form').css({
		'height': 'auto',
		'position': 'relative'
	});
}

We wrap our sticky code to jQuery(window).width(). This code is checking whether our device width is greater than or equal to 768px. That’s how we disable the sticky sidebar for small devices.

Now, there is one more problem. This code run when the page loads, to fix that we’ll wrap this code into function sidebarSticky(). And trigger that function every time the page loads or resizes with JavaScript window.addEventListener.

function sidebarSticky() {
	height = jQuery('.after-header').height();
	if(jQuery(window).width() >= 768) {
		jQuery('.sticky-form').css({
			'height': height - 100,
			'position': 'absolute'
		});
	} else {
		jQuery('.sticky-form').css({
			'height': 'auto',
			'position': 'relative'
		});
	}
}
window.addEventListener('load', function() {
	sidebarSticky();
});
window.addEventListener('resize', function() {
	sidebarSticky();
});
Picture of How to Make Sidebar Sticky Using CSS & jQuery?

Worked like charm! Share your valuable comments or if you are facing any issues let me know.

Leave a Reply

%d bloggers like this: