I know about the positioning of div (fixed, absolute and relative). I can attach a fixed div to body so that it will stick to the same position while scrolling body. Here I am asking a little bit different question.
I have a sidebar with height more than the height of viewport and I want it to be fixed to the body. While scrolling the body, it should also scroll but once the bottom of the fixed div visible, it should not scroll along with body.
For example, the right sidebar of Facebook wall scrolls along with body and stops scrolling with body once the bottom of the right sidebar visible (fixed).
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
That is possible by placing your sidebar absolute and change that to fixed as soon as the windows scroll position passes the bottom.
The CSS:
#sidebar {
height: 120%;
width: 100px;
border: 2px solid blue;
padding: 20px;
margin: 20px;
position: absolute;
top: 0;
}
The jQuery:
$(document).ready(function() {
var bottomPos = $('#sidebar').outerHeight(true) - $(window).height();
$(window).scroll( function() {
if ( $(window).scrollTop() > bottomPos ) {
$('#sidebar').css({'position':'fixed','top':'auto','bottom':'0px'});
} else {
$('#sidebar').css({'position':'absolute','top':'0px'});
}
});
});
And a demo.
Here you have three tutorials for the intended task (first results out of google with query: "fixed sidebar on scroll")
http://www.waypointarts.com/blog/2013/06/29/fixing-a-side-bar-while-scrolling-until-bottom
http://andrewhenderson.me/tutorial/jquery-sticky-sidebar/
http://css-tricks.com/scrollfollow-sidebar/
Here is the code for one of the approaches:
CSS
#page-wrap {
width: 600px;
margin: 15px auto;
position: relative;
}
#sidebar {
width: 190px;
position: fixed;
margin-left: 410px;
}
jQuery
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With