Nick Maddren Nick Maddren - 6 months ago 10
jQuery Question

Should I add an 'if' statement to jQuery that doesn't execute on certain pages?

I like to keep my code clean as possible and I am just wondering what would be the best way to go around this problem when it comes to best practices.

I have the following function:

$('.car-hub-header-help, #assistance-overlay').click(function(){
$('#new-car-hub, #new-car-offer').toggleClass('assistance-active');
$('#pulman-assistance').toggleClass('pulman-assistance-active').css("top", fixedPositionCalculator);
$('#assistance-overlay').toggleClass('assistance-overlay-active');
$('#new-car').toggleClass('assistance-active-body');
$('#new-car-offer-cta').toggleClass('assistance-active-cta');
});


Now as you can see this function is very simple it just toggles classes based on a click event. One issue that I am having is that the element
new-car-offer-cta
is only on specific pages and it seems like this is bad practice to run that part of the function if the element isn't on some of my pages.

So I am just wondering if this would be better practice:

$('.car-hub-header-help, #assistance-overlay').click(function(){
$('#new-car-hub, #new-car-offer').toggleClass('assistance-active');
$('#pulman-assistance').toggleClass('pulman-assistance-active').css("top", fixedPositionCalculator);
$('#assistance-overlay').toggleClass('assistance-overlay-active');
$('#new-car').toggleClass('assistance-active-body');

var carOfferCta = $('#new-car-offer-cta');
if (carOfferCta.length) {
carOfferCta.toggleClass('assistance-active-cta');
};
});


So that part of the function wont run unless the element is on the page. I am just wondering what is classed as the best practice. Thanks

Answer

jQuery already does that check for you, if the selector inside $() doesn't match any elements, the functions you chain to it won't do anything (not even produce an error). So there's really no need to check explicitly. With these exceptions:

  • if you want it to be absolutely obvious to anybody reading your code, that the element you're trying to create won't exist on every page that uses your script or
  • if you want to do a bunch of different things in your if statement,

then it makes sense to explicitly write if ($element.length).

Comments