Here’s what I’m trying to achieve:
I have a div that switches between fixed and absolute positioning depending on the scroll position. I have an example that works but I noticed that it’s a little slow because it constantly changes the position on each and every pixel of scroll. So I thought that adding an additional if statement (as kind of a on and off switch) would remedy it a bit. But of course it broke.
I rarely use jquery/javascript so to my eyes this seems right but it’s not.. any help? Maybe there’s even a better way of doing this than if statements.
var top = blah;
var bottom = blah;
var ison=0;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top && y <= bottom) {
if (ison===0) {
$('#float-contain').addClass('fixed');
var ison = 1;
}
} else {
if (ison===1) {
$('#float-contain').removeClass('fixed');
var ison = 0;
}
}
});
I think the slowness is due to repeated
document.getElementByIdcalls due to$('#float-contain'). You can cache the jQuery object so that you don’t do it.addClass/removeClass/toggleClassdoesn’t do anything if the element already has/doesn’t have the class.This should work just fine:
You can also make this code run when the user has finished scrolling instead of running continuously or you can ‘throttle’ it to run only once per say 100ms. Here’s a way to achieve the first technique – http://www.matts411.com/post/delaying_javascript_event_execution/