How to Create a jQuery Scroll Div (Floating Sidebar)

Posted on March 11, 2014 by Dan Doicaru in jQuery/JavaScript Category

In this tutorial you will learn how to create a jQuery scroll div (floating sidebar) that follows your screen when you scroll down after a certain amount of height in pixels.

This technique is great to use when you have something to advertise or keep some items from sidebar visible, while user is viewing the content. You can also watch the Full HD Video Tutorial.

Video Tutorial

In order to make the jQuery scroll div script working you will need jQuery library included. It's recommended to use the latest file version directly from jquery.com.

Writing the HTML Part for jQuery Scroll Div

The html structure is pretty simple. You must have a <div> inside another <div> with a big height. For example, if you have a big article and your sidebar remains empty when you scroll down, than you can use this <div> to appear when the sidebar content is not covering the whole article.

First make sure to add jQuery. Add the code below between <head> tags. You can also download the jQuery file and use it locally or you can use it direcly from their servers. If you are using WordPress, the latest version comes with a built in jQuery so you don't need to import anything.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

To have a vision of what we are talking about we will use the html code only for the sidebar jQuery scroll div. Take a look at the html code below:

<div class="sidebarBox">
	<h3>Some Widget Title</h3>
	<br />
	<div class="scrollingBox">
		<h3>A Big Heading Text</h3>
		<img src="an-image.jpg" alt="inside the scrolling box">
		<br /><br />
		<p>Some text inside the scrolling box</p>
	</div>
	<br />
	<h3>Some Text</h3>
	<p>A paragraph full of text</p>
</div>

In the html code above, inside the "sidebarBox" div is its content and another div with the class "scrollingBox". That div with the class "scrollingBox" will appear only when you scroll down after a certain amount of pixels. We will only set its position to fixed to be sticked to the top when the user will scroll down.

Adding the Basic CSS

You can style the box however you want, but make sure to have the styles below:

.sidebarBox {
	width: 300px; /* Replace with your sidebar width */
	float: right;
	position: relative;
}
.scrollingBox {
	width: 300px; /* Replace with the same width as sidebar */
}

Add jQuery Function for Floating Sidebar

To make it work, add the script below, right above the ending tag of <body> or you can add it below the jQuery file import in <head> tag, but is recommended to load any Javascript code  after the html is generated.

<script type="text/javascript">
$(function() {
	// Set this variable with the height of your sidebar + header
	var offsetPixels = 700; 

	$(window).scroll(function() {
		if ($(window).scrollTop() > offsetPixels) {
			$( ".scrollingBox" ).css({
				"position": "fixed",
				"top": "15px"
			});
		} else {
			$( ".scrollingBox" ).css({
				"position": "static"
			});
		}
	});
});
</script>

The "offsetPixels" variable is the amount of height when scrolling down. If you scroll 670 pixels down the first css rules will be applied. If not, the box will be in the same place.

To find the sidebar height, right click on the first text from the sidebar and inspect the code. Search your sidebar div in the html source code and put the mouse over it to indicate the dimensions, or you can simply go to "Computed" tab in Chrome Browser. Check the image below.

inspect-code-google-chrome

Update (13 Jun 2015)

You can also calculate the scroll top amount automatically, by using outerHeight() function to get the sidebar height, plus adding the header height. Basically you must set scroll top value from the first top of the page until the sidebar ends.

// set the offset pixels automatically on how much the sidebar height is.
// plus the top margin or header height

var offsetPixels = $('.sidebarBox').outerHeight() + 40;

Simply update the variable with the code above. Also if your site is responsive you can either create 2 different divs and hide them with @media queries or keep one div for all version but you will need to tweak the script a little.

To see a sample of how this jQuery scroll div code will work you can check the live demo page below or download the source files.

Live Demo

Download Files

Rate & Share
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 4.50 out of 5)
Related Articles
Comments
  1. Gravatar Icon Weks:

    Hello! Nice tutorial, maybe you can help me to do a thing… :D

    $(function() {
    	var offsetPixels = $('.page-title').outerHeight() + 20;
    
    	$(window).scroll(function() {
    		if ($(window).scrollTop() > offsetPixels) {
    			$('body').removeClass('scrolltop').addClass('scrolling');
    		} else {
    			$('body').addClass('scrolltop').removeClass('scrolling');
    		}
    	});
    });

    Working very nice, but I want to add a padding to a div (.container). This padding should be the height of the var declared above.

    I think it’s really easy, but I don’t know jQuery :D Thanks !

    • Hello Weks,

      Your code is fine like that. You got the height of the container and you added 20, which I suppose is the padding.

      Not sure exactly what do you want to do, but if you want to add the padding, just add the padding value there in your variable, which is 20.

  2. Gravatar Icon Yogi Grantz:

    My approach is a bit different, I do it this way:

    First I keep the current scroll in a var, then whenever I am showing a result, I scroll the box slowly using animate. The code goes like this:

    var currentScroll = 0;
    
    $(window).scroll(function () {
    	currentScroll = $(window).scrollTop();
    });
    
    var showSnippetNicely = function() {
    	$(".floatBoxSnippet").animate({ "top": currentScroll }, 200);
    };
    • Hello Yogi,

      Your script is fine, but it needs some tweaks. First of all the last function it runs only one time and we need to run it in real time to update the scroll value. My personal opinion is that animated floating container just slows the browser, because of the instant calculation and inline css rewrite.

      • Gravatar Icon Yogi Grantz:

        Absolutely, I created that for one time shot so when I click my snippet link at a scrolled position, the snippet box will ease down on me, then when I scroll up, and click on another snippet link, the snippet box will ease up on me. In order to make the div follow the scroll, all we need to do is add this one line statement under the line “currentScroll = …”

        showSnippetNicely();

        This will make the box follow your scroll easily. However, when the box is not displayed initially, and you scroll, then click on the snippet link, it will show up at the designated position right away, without the animation effect. Thank you for checking my post and allowing me to post on your site, you’re awesome!

  3. Gravatar Icon Black:

    Thanks for the tutorial, he served me, but in my case how to do that when you reach a bottom point at which surpasses above the other div stay static again, or as they have structured here in this site cubadebate.cu. I hope urgent answers…

    • Hello Black,

      Sorry for my late answer, was a bit busy. The problem with your sidebar: it is too big in height even for 1080p monitors and to stop the fixed position when you reach the footer, you need to use .offset().top to calculate the initial sidebar position together with the footer. Then you need to do some math with the 2 offsets and sidebar height and some if functions.

  4. Gravatar Icon Jennifer:

    Just an FYI: I have a fixed top strip on my site, and this code didn’t work with that.
    When I removed the top fixed div, this worked. Any workaround to this?

    Thanks.

  5. Gravatar Icon Pratt:

    Usually I don’t write comments, but I wanted this was the exception. I have been searching for a guide on how to do exactly what you’ve just done for about a week now, and I had almost given up on my sticky sidebar until I found yours.

    Thanks for your help!

  6. Gravatar Icon Louis:

    Thanks – simple and to the point.
    Could scan quickly through and grab what I needed – without any lengthy tutorial

Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.


+ 6 = 7

Search
Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (extremestudio.ro), built under WordPress platform.