Ilja
Ilja

Reputation: 46479

How to make div scroll down with a page once it reaches top of page?

I know title is a bit confusing ;D but basically what I want to do is clearly demonstrated on this website http://9gag.com scroll down and pay attention to sidebar, there are 2 advertisements once 2nd advertisement reaches top of the page it starts scrolling down with a page.

I would like to know how to do this? html/css or jQuery solutions are prefared.

Upvotes: 5

Views: 7528

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

As Kevin points out, what you need to do is to listen to the document's scroll event. When that is fired, you'll want to look at the value of scrollTop.

$(document).scroll(function() {

    var useFixedSidebar = $(document).scrollTop() >= myThresholdValue;
    $('.my-sidebar-items').toggleClass('fixed', useFixedSidebar);

});

And your CSS would basically look like this:

.my-sidebar-items.fixedSidebar { position: fixed; }

A complicating factor is that you'll probably want the items to be fixed in their new, top positions, and you would want to do something like this:

.my-sidebar-items.fixedSidebar { position: fixed; top: 0 }

However, that would probably stack your items on top of one another. A solution to that would be to put the fixedSidebar class on a container, and use the class as described.

Demo

Upvotes: 7

eveevans
eveevans

Reputation: 4460

You could use sticky bars http://archive.plugins.jquery.com/plugin-tags/sticky or jQuery Waypoints http://imakewebthings.github.com/jquery-waypoints/

Upvotes: 2

Related Questions