I have a variable that I would like to not affect condition or donot charge when necessary, ie when not in this case the DIV # sidebar
My code is:
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('margin-top').replace(/auto/, 0));
var _height = $('#sidebar').height();
var _original_top = $('#sidebar').offset().top;
$(window).scroll(function(event) {
var y = $(this).scrollTop();
var z = $('footer').offset().top;
if (y >= top && (y + _height) < z) {
$('#sidebar').removeClass('stuck-bottom').addClass('fixed');
} else {
if ((y + _height) > z) {
$('#sidebar').removeClass('fixed').addClass('stuck-bottom');
}
else $('#sidebar').removeClass('stuck-bottom').removeClass('fixed');
}
});
If I put this code does not work: (
if ($('#sidebar')) { ... }
If the problem is that your
ifalways executes the code, you need to change how you detect if#sidebarexists. This may be because$('#sidebar')will usually evaluate to true, even if there are no matching elements, because$()returns a valid jQuery object. To have the condition only succeed when#sidebaractually exists, try:However, if your problem is that the condition never succeeds even if
#sidebarexists, your code may be getting executed before the DOM has loaded. You’ll need to wrap your code in a$.ready()function, so it doesn’t execute until the page has been downloaded, parsed and rendered: