Get our posts emailed to you with our monthly newsletter, subscribe here.

This tutorial will show you how to implement a jQuery sticky sidebar, the sidebar will slide up and down the screen respective to which way you are scrolling, this way the sidebar always sits at the top of the window.

This is a great feature to add to your site, as it allows for the sidebar content to always be in view of the user, this is great for displaying ads or additional content.

Step 1 – Creating the basic HTML

Nothing advanced here, we are setting up a basic HTML page for demonstration purposes.

Note: As this plugin will need the jQuery libary, I have included it in between the <head></head> tags. I am pulling in the libary which is hosted by Google using this line –

[javascript]<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>[/javascript] [html] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Floating sidebar</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" media="all" href="style.css" />
</head>

<body>

</body>
</html>
[/html]

Step 2 – Add the script from – Smart sticky floating box

Follow the link and download the plugin, the code we are using is below. For this demonstration, I will insert this script right before the closing </body> tag.

[javascript] <script type="text/javascript">
/*
* stickyfloat – jQuery plugin for verticaly floating anything in a constrained area
*
* Example: jQuery(‘#menu’).stickyfloat({duration: 400});
* parameters:
*         duration     – the duration of the animation
*        startOffset – the amount of scroll offset after it the animations kicks in
*        offsetY        – the offset from the top when the object is animated
*        lockBottom    – ‘true’ by default, set to false if you don’t want your floating box to stop at parent’s bottom
* $Version: 05.16.2009 r1
* Copyright (c) 2009 Yair Even-Or
* vsync.design@gmail.com
*/

$.fn.stickyfloat = function(options, lockBottom) {
var $obj                 = this;
var parentPaddingTop     = parseInt($obj.parent().css(‘padding-top’));
var startOffset         = $obj.parent().offset().top;
var opts                 = $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);

$obj.css({ position: ‘absolute’ });

if(opts.lockBottom){
var bottomPos = $obj.parent().height() – $obj.height() + parentPaddingTop; //get the maximum scrollTop value
if( bottomPos < 0 )
bottomPos = 0;
}

$(window).scroll(function () {
$obj.stop(); // stop all calculations on scroll event

var pastStartOffset            = $(document).scrollTop() > opts.startOffset;    // check if the window was scrolled down more than the start offset declared.
var objFartherThanTopPos    = $obj.offset().top > startOffset;    // check if the object is at it’s top position (starting point)
var objBiggerThanWindow     = $obj.outerHeight() < $(window).height();    // if the window size is smaller than the Obj size, then do not animate.

// if window scrolled down more than startOffset OR obj position is greater than
// the top position possible (+ offsetY) AND window size must be bigger than Obj size
if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){
var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
if ( newpos > bottomPos )
newpos = bottomPos;
if ( $(document).scrollTop() < opts.startOffset ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
newpos = parentPaddingTop;

$obj.animate({ top: newpos }, opts.duration );
}
});
};

$(‘#menu’).stickyfloat({ duration: 400 });
</script>
[/javascript]

Step 3 – Add content

I shall now add content to the page, using a div based layout, I have created 4 different divs – ‘header’, ‘content’ ‘menu’, ‘footer’. The div we will be looking at to scroll up/down the page will be the ‘menu’. Your page will now look like so –

[html] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Floating sidebar</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" media="all" href="style.css" />
</head>

<body>

<div>d<span>w</span></div>

<div>

<div id="menu">Archives</div>

<div>

<h1>Smart sticky floating box</h1>

<p><strong>Scroll down, the ‘archives’ sidebar will follow!</strong></p>

<p>Want your box to float beside you as you scroll, but ONLY in a specific constrained area? or only on it’s parents area? – you got it.</p>

<ul>
<li>Extremely useful for side-menus</li>
<li>All in one vertical floating solution</li>
</ul>

<p>Parameters:</p>

<ul>
<li>duration – the duration of the animation</li>
<li>tartOffset – the amount of scroll offset after it the animations kicks in</li>
<li>offsetY – the offset from the top when the object is animated</li>
<li>lockBottom – ‘true’ by default, set to false if you don’t want your floating box to stop at parent’s bottom</li>
</ul>

<p>Example:</p>

<p>jQuery(‘#menu’).stickyfloat({duration: 400});</p>

<br />

<p><a href="">Back to post</a> | <a href="http://plugins.jquery.com/project/stickyfloat">Download jQuery Plugin<a></p>

</div>

<div>Footer</div>

</div>

<script type="text/javascript">
/*
* stickyfloat – jQuery plugin for verticaly floating anything in a constrained area
*
* Example: jQuery(‘#menu’).stickyfloat({duration: 400});
* parameters:
*         duration     – the duration of the animation
*        startOffset – the amount of scroll offset after it the animations kicks in
*        offsetY        – the offset from the top when the object is animated
*        lockBottom    – ‘true’ by default, set to false if you don’t want your floating box to stop at parent’s bottom
* $Version: 05.16.2009 r1
* Copyright (c) 2009 Yair Even-Or
* vsync.design@gmail.com
*/

$.fn.stickyfloat = function(options, lockBottom) {
var $obj                 = this;
var parentPaddingTop     = parseInt($obj.parent().css(‘padding-top’));
var startOffset         = $obj.parent().offset().top;
var opts                 = $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:true }, options);

$obj.css({ position: ‘absolute’ });

if(opts.lockBottom){
var bottomPos = $obj.parent().height() – $obj.height() + parentPaddingTop; //get the maximum scrollTop value
if( bottomPos < 0 )
bottomPos = 0;
}

$(window).scroll(function () {
$obj.stop(); // stop all calculations on scroll event

var pastStartOffset            = $(document).scrollTop() > opts.startOffset;    // check if the window was scrolled down more than the start offset declared.
var objFartherThanTopPos    = $obj.offset().top > startOffset;    // check if the object is at it’s top position (starting point)
var objBiggerThanWindow     = $obj.outerHeight() < $(window).height();    // if the window size is smaller than the Obj size, then do not animate.

// if window scrolled down more than startOffset OR obj position is greater than
// the top position possible (+ offsetY) AND window size must be bigger than Obj size
if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){
var newpos = ($(document).scrollTop() -startOffset + opts.offsetY );
if ( newpos > bottomPos )
newpos = bottomPos;
if ( $(document).scrollTop() < opts.startOffset ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
newpos = parentPaddingTop;

$obj.animate({ top: newpos }, opts.duration );
}
});
};

$(‘#menu’).stickyfloat({ duration: 400 });
</script>
</body>
</html>

[/html]

The plug-in will look for the div with ID of ‘menu’ and apply the effect…

The full documentation and plug-in download can be found at – http://plugins.jquery.com/project/stickyfloat

See it in action – Demo

Posted by David Martin

David Martin is a Web Developer & Designer from the UK with a love for minimal design, coffee and WordPress - catch up with David on Twitter.

12 Comments

  1. hey, i cannot get this to work in IE7? Works great in all mac browsers? can you point me in the direction off code i need?

  2. Very helpful and without being bloatware to boot. Works nicely in IE7,8,9, FF4 and Chrome.

  3. I love the plugin, best working one so far. The only issue is if the sidebar is to tall. When you scroll down a bit, the sidebar is pushed from the top, and if there is content in the bottom of the sidebar that you want to see, you cannot see it until you get all the way to the footer, which then stops the sidebar pushing from the top, so you can scroll down enough to see the content in the bottom of the sidebar.

  4. Say I didnt want the animation and set the duration to 0. How can I make it smooth, and not “jumpy” as it scrolls?

  5. OK after some more digging I have made some progress:

    1) Changed all instances of $ to jQuery
    2) added sticky javascript at the end of all s in the sidebar(dot)php file
    3) Modified #sidebar attributes to position: absolute; left: 650px;

    Good news is that the sidebar lines up and does scroll.
    Bad news is the scroll is not set up as it should be.

    You can view my demo here:
    http://demos.elementalmedia.biz/opm

    I am very close, just needs a little tweaking.
    Thanks in advance for any and all help.

  6. Thanks for the tutorial, but I am having a tough time incorporating this into my WordPress theme. The HTML example you give is great, but I am dealing with a wordpress theme that has the following php files:

    header(dot)php
    page(dot)php
    sidebar(dot)php

    I added the google hosted version of jQuery to the header(dot)php file. There was some other js file references there already:

    tools(dot)js
    easing(dot)js
    jquery(dot)prettyPhoto(dot)js
    swfobject(dot)js
    cycle(dot)js
    nivo(dot)js
    accordion(dot)js
    superfish(dot)js
    validate(dot)js
    custom(dot)js

    I am confused as to where to place the stickyfloat script.
    Should I put it on the page(dot)php file or the sidebar(dot)php file?

    Also when I reference the div I want to target (#sidebar), it has no effect. I moved the position of the block of script to another part of the sidebar(dot)php file, and it moved my sidebar flush to the left of the page and did not stay in a fixed postiton then.

    Could you please advise as to proper placement in a WordPress theme? Thanks again and sorry if I was a little long winded.

  7. Awesome, I’m digging this David. Cheers for the tutorial

  8. thank you a lot man

    1. No problem!
      -David

  9. Hey, thanks..
    I was trying to do this for a while..!!

    Thanks a lot!! :D

    1. No problem, with this method its really easy to do.

Comments are closed.