jquery only fire if div#sidebar exists on page
I'm using the following code to control a div with the ID 'sidebar'
开发者_Python百科var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').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
$('#sidebar').addClass('fixed');
} else {
// otherwise remove it
$('#sidebar').removeClass('fixed');
}
});
However when a page that odes not contain div#sidebar it throws out an error stating #sidebar is null (because it's not there!)
How can I convert this code to only happen IF there is div#sidebar on the page?
If I am not wrong you can use
if ($('#sidebar').length > 0){
.............
}
to achieve that.
if($('#sidebar').length > 0)
{
//your code here
}
You can reduce your code down using .length
to check if it exists and cache the selector, like this:
var sb = $('#sidebar');
if(sb.length) {
var top = sb.offset().top - parseFloat(sb.css('marginTop').replace(/auto/, 0));
$(window).scroll(function () {
sb.toggleClass('fixed', $(this).scrollTop() >= top);
});
}
.length
returns the number of elements the selector found, if it's not there it'll be 0
or false
for the purposes of our if()
check. After that we're using .toggleClass(class, bool)
to more tersely add or remove the class based on the scroll positon.
You can try this.
if($('#sidebar').size > 0){
//your code
}
精彩评论