Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

css

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.

like image 339
Ilja Avatar asked Dec 22 '11 18:12

Ilja


People also ask

How do you automatically scroll to the bottom of a div?

// To scroll to the bottom of a div const theElement = document. getElementById('elementID'); const scrollToBottom = (node) => { node. scrollTop = node. scrollHeight; } scrollToBottom(theElement); // The specified node scrolls to the bottom.

How do you keep a div at the top of the page when scrolling?

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

How do I make my div overflow scroll?

For vertical scrollable bar use the x and y axis. Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable.

How do you scroll down to the bottom of a page?

No, by far the best way to jump to the top or bottom of a Web page is by tapping your Home or End key, respectively. This works in Chrome, Firefox, and Internet Explorer (and probably every other browser as well–those are just the ones I've tested). Try it–I guarantee it'll join your list of favorite shortcuts.


2 Answers

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

like image 63
David Hedlund Avatar answered Oct 05 '22 23:10

David Hedlund


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

like image 33
eveevans Avatar answered Oct 06 '22 00:10

eveevans