I’m trying to imitate how gMail sticks the header to the top on scroll, when going past a certain part.
The code:
$(window).scroll(function() {
$('.the-post').each(function() {
var elem = $(this),
y = $(window).scrollTop(),
maxY = elem.children('.body').offset().top,
header = elem.children('.header'),
scrollHeight = 24;
if(y >= maxY-scrollHeight) {
$('.afloat').remove();
header
.clone()
.appendTo('.post')
.addClass('afloat');
setSizes()
} else $('.afloat').remove()
})
})
I’m using .clone() because I don’t want to interrupt the heighth of the page. When just adding the class, there’s a slight nudge and it’s exactly what I want to avoid.
However, it only does it on ONE of the posts. Can someone see why?
I also want to stop running the function once the header is there and the window is within boundaries.
UPDATE
So I figured this out. The problem with the above code was the else statement, it was removing the divs too fast. I improved it quite a bit and would love some more input, but this is working well and without overload:
$(window).scroll(function() {
var y = $(this).scrollTop();
if(y >= maxY-24) {
if(!isset) {
isset = true;
$('.post').append(header
.clone()
.addClass('afloat')
)
}
$('.the-post').each(function() {
var elem = $(this),
maxY = elem.children('.body').offset().top,
header = elem.children('.header');
if(y >= maxY-24 && y <= maxY+24) {
newtext = header.children('em').text();
if(newtext != curtext) {
curtext = newtext;
$('.afloat').text(newtext)
}
}
})
} else {
isset = false;
$('.afloat').remove()
}
})
I had to re-do the logic here. I created the static header right away once applicable, so that I do not have to keep cloning divs.
Then I run through the divs (.the-post) with each, and made it a range-method so to prevent extra, useless queries.
The answer is: