Reputation: 452
I store all javascript code which deals frontend part of app in frontend.js. If dom element does not exist on this page but i try apply plugin javascript throw error Sample:
$('#normalImage').Jcrop({
setSelect:[ 0, 0, 48, 48 ],
sideHandles:false,
onChange:showPreview,
onSelect:showPreview,
aspectRatio:1
});
I found one solution for this problem it's check size
if($('#normalImage').size() > 0)
//apply plugin
But i'm not sure what is right way
Upvotes: 1
Views: 328
Reputation: 639
If you want to check if a dom element exists you could use:
if ( $("#normalImage").length > 0 ) {
//do something
}
Upvotes: 0
Reputation: 14874
It's the right way to check the .length and comapring it with zero to check if the collection has any element or not?
From jquery site:
The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.
Upvotes: 1
Reputation: 14782
You're probably dealing with a bad plugin as it's the plugins job to not throw an error when the jquery selector is empty. But in this case checking the size or length is the correct way for it to work.
Best use this:
var dom = $('#normalImage');
if(dom.length > 0)
{
dom.Jcrop({
setSelect:[ 0, 0, 48, 48 ],
sideHandles:false,
onChange:showPreview,
onSelect:showPreview,
aspectRatio:1
});
}
Upvotes: 4