Reputation: 31
I have made a div witin div, i want the inner div to float up and down on scrolling page up and down within the outer div. I have somehow managed to make it restrict not to go out of the outer div form to but when it comes to bottom it goes down till bottom of the page. please help me, here is my code css
CSS
#comment {
position: absolute;
/* just used to show how to include the margin in the effect */
}
HTML
<!--the outer div in which i have whole content -->
<div class="content">
<!--the floating div, remains well inside form top but moves down outside div from bottom -->
<div class="ftwrapper" id="comment">
</div><!--fb/twitter ends-->
</div>
JQuery
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#comment').offset().top - parseFloat($('#comment').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('#comment').addClass('fixed');
} else {
// otherwise remove it
$('#comment').removeClass('fixed');
}
});
}
});
Upvotes: 3
Views: 2509
Reputation: 3753
I made a sample test based on your requirement. It doesnt work well if scrolled too fast, but otherwise its ok. Ill make some changes to it later.
var prevScroll = 0;
$(window).unbind("scroll");
function reposition() {
var contPos = $("#container").offset();
var comment = $('#comment');
contPos.bottom = contPos.top + $("#container").outerHeight();
console.log('contPos',contPos);
$(window).scroll(function (event) {
// what the y position of the scroll is
var scroll = $(window).scrollTop()
, y = scroll
, pos = comment.offset()
;
pos.bottom = comment.outerHeight();
if ( scroll > prevScroll) {
//down
} else {
//up
}
prevScroll = scroll;
// whether that's below the form
console.log(pos.bottom + scroll ,":", contPos.bottom);
if (contPos.top > scroll) {
// if so, ad the fixed class
comment.css({
position: 'relative',
bottom : '0px',
left : '0px'
});
console.log("Too High");
} else if ( pos.bottom + scroll > contPos.bottom) {
//comment.removeClass('fixed');
comment.css({
position: 'absolute',
top : (contPos.bottom - comment.outerHeight() )+'px',
left : pos.left+'px'
});
console.log("Too Low");
} else {
// middle area
console.log("Perfect");
comment.css({
position: 'fixed',
top : '0px',
left : pos.left + 'px'
});
}
});
}
$(document).ready(reposition);
Upvotes: 1