Reputation: 2194
I have a DIV which needs to stay on the page as much as possible when the user is scrolling down. It starts off inside it's parent div at the top. Then when the user scrolls, it needs to stay where it is on the page, until it hits the bottom of the div, where it must stop scrolling on the page and then accept it's fate by scrolling off of the top of the page.
Confused? Me too. Here is a paint diagram of what I will like to happen on scroll:
Here is what is currently happening:
Here is the bodged jQuery that I am using to achieve something near this:
//Start div scrolling
if ($(this).scrollTop() > 420 && $(this).scrollTop() < 1200) {
$('.fixedElement').css({
'position': 'fixed',
'top': '0px'
});
}
//Stop div scrolling
if ($(this).scrollTop() < 420) {
$('.fixedElement').css({
'position': 'static',
'top': '0px'
});
}
//Div to stop scrolling as div will leave the parent div otherwise. Master does not want that.
if ($(this).scrollTop() > 1200) {
$('.fixedElement').css({
'position': 'static',
'top': '',
'bottom': '0px'
});
}
however, I have am needing to guess through trial an error when to get the div to stop moving. Is there a better way?
I know this has been asked before and I have researched it, however many of the results just shows how to get it to move, and not how to get it to stop at the bottom of a div.
Upvotes: 4
Views: 2226
Reputation: 5880
If I've understood your problem correctly, you want the inner
div to stay in its position, as far as the screen's top is NOT beyond parent
div's height minus the inner
div's height, then check THIS JSfiddle out.
As such, you'd be just checking the following condition:
if($(this).scrollTop() >= 0 && $(this).scrollTop() < ($('.parent').height() - $('.inner').height())){
//fix the inner div here
} else {
//unfix it
}
Upvotes: 5