05
Aug
2012

Floating jQuery sidebar

Posted in: jQuery , 1 Comment

jquery_logo
You may have seen a floating fixed sidebar in many modern website. In this tutorial I will show how to create a similar type sidebar using jQuery.

Step 1:
Create a basic HTML page with regions Header, Container, siderbar

<header>
<!-- put header content here -->
</header>

<div id="wrap">

<div id="sidebar">
<!-- put sidebar content here -->
</div>

<div id="container">
<!-- put main content here -->
</div>

</div> <!-- end wrap -->

Step 2:
Add CSS to position all regions properly.

header {
	width: 100%;
	height: 100px;
	background: #d7d53f;
	}

#wrap   {
	width: 600px;
	margin: 0 auto;
	}

#sidebar {
	float: left;
	width: 200px;
	background: #c2b3c6;
	margin-left: -220px;
	}

Step 3:
Call jQuery Library.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Step 4:
Now add following jQuery code.

<script type="text/javascript">
$(document).ready(function(){
    var sidebartop = $('#sidebar').offset().top;
    $(window).scroll(function(){
        if( $(window).scrollTop() > sidebartop ) {
            $('#sidebar').css({position: 'fixed', top: '30px'});
        } else {
            $('#sidebar').css({position: 'static'});
        }
    });
});
</script>

Done!!

Check Live demo
Demo Download

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

1 Comment to "Floating jQuery sidebar"

Add Comments (+)
  1. Mak says:

    Hi

    finally I found your post and I believe that this is the solution.

    I have a website with the sidebar on the right handside. using you script the box will jump to the right.

    How can I solve this

    thanks in advance!

Leave a Reply