Reusing a jQuery function without causing an error on pages that do not utilize it
I use this function to make a help box stay visible when a user scrolls down:
var top = $('.help-box').offset().top - parseFloat($('.help-box').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('.help-box').addClass('fixed')开发者_运维知识库;
} else {
$('.help-box').removeClass('fixed');
}
});
I want to reuse it across several pages, so I included it in my layout (on every page load). The problem now is that I get an error on pages that do not have the help box: $(".help-box").offset() is null
Is there a way to write this function so it can be reused without causing an error? I want to avoid selectively including where it's need it as it's easier to just leave the include in my layout.
var helpBox = $(".help-box"), top;
if(helpBox !== null && helpbox != undefined && helpBox.length > 0) {
top = helpBox.offset();
}
Just check whether you have a helpbox before calling the function.
Put everything in try-catch block:
try
{
var top = $('.help-box').offset().top - parseFloat($('.help-box').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('.help-box').addClass('fixed');
} else {
$('.help-box').removeClass('fixed');
}
});
}
catch(err)
{
}
var helpBox = $('.help-box');
function initHelpBox(){
var top = helpBox.offset().top - parseFloat(helpBox.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
helpBox.addClass('fixed');
} else {
helpBox.removeClass('fixed');
}
});
}
if (helpBox.length){initHelpBox()}
精彩评论