Attaching a side div to the top of a window.

I was working on a site and needed to have a side nav stick to the top once the header was scrolled off the screen.  Positioning it is easy enough on page load, but I wanted to move it with window scroll.

First I generated the div with theside nav items in it.  Positioned it fixed with a right of 0 and a top of my header height of 200px;

Then came the window scroll javascript.  The concept is pretty simple, so I was able to get it to work with this code:

[code language=”javascript”]
(function($) {
$(document).ready( function() {
if ($(this).scrollTop() < 200) {
$(".side-nav").css({ "position": "fixed", "top": 200 – $(this).scrollTop() + "px" });
} else {
$(".side-nav").css({ "position": "fixed", "top": "0px" });
}

$(window).scroll(function() {
if ($(this).scrollTop() < 200) {
$(".side-nav").css({ "position": "fixed", "top": 200 – $(this).scrollTop() + "px" });
} else {
$(".side-nav").css({ "position": "fixed", "top": "0px" });
}
});
});
})(jQuery);
[/code]

A flushed out example of this can be seen at:
http://jsfiddle.net/evermoretech/wChGd/

Leave a Reply

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