Reputation: 1154
Just a quick question.
I'm wondering if in the following code if unslider() will run if there is no .banner class on the page?
jQuery(".banner").unslider();
I do not want it to run on pages where there is no .banner class.
Do I need to do something like
if (jQuery(".banner") > 0){ jQuery(".banner").unslider(); }
Upvotes: 0
Views: 148
Reputation: 173642
Yes, it runs and executes the following (source):
$.fn.unslider = function(o) {
var len = this.length;
// Enable multiple-slider support
return this.each(function(index) {
// Cache a copy of $(this), so it
var me = $(this);
var instance = (new Unslider).init(me, o);
// Invoke an Unslider instance
me.data('unslider' + (len > 1 ? '-' + (index + 1) : ''), instance);
});
};
So it does a .each()
on your collection.
However, if that collection is empty, the function passed to .each()
will not run and therefore "not much" would describe best what would happen if you run $('.banner').unslider();
Btw, it wouldn't make sense to try and "optimize" this by doing a .length
check unless you're certain that the call will be heavy.
Upvotes: 2
Reputation: 67207
Normally the follow up actions wont get executed if the class
is not available, but doing a preliminary check will be safer one.
You have to like this,
if(jQuery(".banner").length > 0){ jQuery(".banner").unslider(); }
Or
if(jQuery(".banner").length){ jQuery(".banner").unslider(); }
Upvotes: 0
Reputation: 148150
You need to use the length
property to check if element exists.
if (jQuery(".banner").length > 0)
{
jQuery(".banner").unslider();
}
You even do not need to check if it is greater then zero.
if (jQuery(".banner").length)
{
jQuery(".banner").unslider();
}
Upvotes: 0
Reputation: 388406
No, it will not get executed if the element is not found.
The plugin method will get called, but since there are no element matching the selector it should not be doing anyting - but it again depends on how the plugin is implemented
Upvotes: 0