Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I stick the div after scrolling down a little

Tags:

I wanted to stick the 2nd div when we scroll down the page and when the 2nd div meets the top boundary. When it's fixed, it should scroll along with the other pages. How can I achieve this?

#settings{     width:100%;     background:#383838;     height:60px; } #menu{     width:100%;     position:relative;     height:100px;     background:#aaa; } #body-content{     height:900px;     position:relative; } 

and the HTML

<body> <div id="top">     <div id="settings">     </div>     <div id="menu">     </div> </div> <div id="body-content"> </div>  </body> 

Here in this example http://jsfiddle.net/WBur3/ , the 2nd div should be fixed when we scroll the page. When we scroll up, should turn into the previous state itself. Please help me.

like image 552
user1012181 Avatar asked Jan 24 '13 07:01

user1012181


People also ask

How do you stick a div after scrolling?

The element is set to 'fixed' or 'relative' depending upon whether the user has scrolled past the element. The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position.

How do I keep my div sticky?

To make an element sticky, do: make_sticky('#sticky-elem-id'); When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

How do you make a div sticky at the bottom?

Set the position of div at the bottom of its container can be done using bottom, and position property. Set position value to absolute and bottom value to zero to placed a div at the bottom of container.


1 Answers

You can get this effect with jquery

$(function(){         // Check the initial Poistion of the Sticky Header         var stickyHeaderTop = $('#stickyheader').offset().top;          $(window).scroll(function(){                 if( $(window).scrollTop() > stickyHeaderTop ) {                         $('#stickyheader').css({position: 'fixed', top: '0px'});                         $('#stickyalias').css('display', 'block');                 } else {                         $('#stickyheader').css({position: 'static', top: '0px'});                         $('#stickyalias').css('display', 'none');                 }         });   }); 

DEMO HERE

NOTE: Don't forget to include jquery library link in your page (assuming you as beginner)

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> 
like image 161
Sowmya Avatar answered Sep 24 '22 18:09

Sowmya