Keep an element fixed within a container during window scroll

jkilp picture jkilp · Feb 9, 2012 · Viewed 12.5k times · Source

I have a question that I think will be best explained using an image, so I am going to attach it.

enter image description here

Ok, so basically what I have is a parent container, and an element inside it (it will actually be a block of text), which we will refer to as the FIXED element.

When the user is at the top of page, I want the fixed element to be at the top of its parent. When the user starts scrolling down the page, and the parent starts moving up the view port, I want the fixed element to follow the scrolling until it reaches the bottom of its parent, then it stops there.

There currently is no HTML or anything for this yet, because I'm in the rough sketching stage of this website.

I am open to using jQuery or javascript in general, my JS skills are limited, and I am familiar with jQuery, but I don't mind copying and pasting code and messing with it.

Any help will be greatly appreciated. Thanks!

Answer

thenetimp picture thenetimp · Feb 9, 2012

What you want to do using javascript (with or without jQuery) is change the position of the element absolutely against the position of the parent, the parent should be relative. You change the position based on the position of the scrollbar.

This tutorial has a good explanation of how to accomplish that.

http://www.wduffy.co.uk/blog/keep-element-in-view-while-scrolling-using-jquery/