user1405690
user1405690

Reputation: 149

jQuery : Make Automatically Scrolling Div

Can anyone tell me how to implement the scroll 'sidebar' follows the users scrolling the page, but stops when it reached the 'footer'

<div id="section">
    <div id="sidebar"> </div>
    <div id="hello"> </div>
</div>
<div id="footer"> </div>

Div 'section' doesn't have a set height meaning it grows whenever the div with an id of hello grows. This means that neither the 'hello' nor 'section' has a set height

Div 'section' has a width of 728 and 'hello' has a width of 400. 'sidebar' has a width of 200.

What I want to happen is (using jquery) when the person scrolls just a little past the sidebar then the sidebar should scroll with the page. Hoever the sidebar should not overlap with the footer.

Therefore sidebar should only scroll along with the page till the end of the div section.

The red block (on my website) is the sidebar that want to scroll.

Upvotes: 0

Views: 671

Answers (1)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

Something like the following should get you started (Tested CHROME only): http://jsfiddle.net/MyFB9/3/

JS

var $sb = $('#sidebar'); 
var $foot = $('#footer');
var footerTop = $foot.offset().top;
$foot.html(footerTop);
$(document).scroll(function(){
    //+ 100 since the height of the sidebar is 100px

    if($(this).scrollTop() + 100 > footerTop){
        //when we get close, line up perfectly with the footer
        $sb.css({top:footerTop - 100}); 
    }else{
        //otherwise scroll with the page
        $sb.css({top:$(this).scrollTop()}); 
    }

    //Visualy display the position of the bottom edge of the sidebar
    $sb.html($sb.offset().top + 100)
});

HTML

<div id="section">
    <div id="sidebar"> </div>
    <div id="hello"> </div>
</div>
<div id="footer"> </div>​

CSS

#section{
 vertical-align:top;   
}
#sidebar, #hello{
 display:inline-block;
 position:relative;    
 vertical-align:top; 
 top:0px;
 left:0px;   
}
#sidebar{
 height:100px; 
 width:50px;
 background-color:red;   
}
#hello{
 height:900px; 
 width:50px;
 background-color:green;   
}
#footer{
 height:450px;
 width:100px;
 background-color:yellow;    
}
​

Upvotes: 1

Related Questions