Reputation: 25348
When using third-party plugins, I typically initialize them in my main application.js
file.
Example:
$('.scroll').jScrollPane();
The problem is if a page loads that doesn't have the scroll
class, then I get:
TypeError: Result of expression '$('.scroll').jScrollPane' [undefined] is not a function.
So to get around this, I wrap it in:
if ($(".scroll").length){
$('.scroll').jScrollPane();
}
That remedies the problem but just seems like a hack.
Is there a "correct" way to solve this?
Upvotes: 2
Views: 712
Reputation: 322502
If you're getting:
ScrollPane' [undefined] is not a function.
...it wouldn't be because the page doesn't have a .scroll
element.
That sort of error occurs when the plugin (or jQuery itself) isn't loaded.
If you're reusing some code on several pages, some of which don't have that plugin, do this instead:
if ( $.fn.jScrollPane ){
$('.scroll').jScrollPane();
}
Upvotes: 2
Reputation: 32726
As a couple others have said, that error is the jScroll's error. If it's because an element doesnt exist jQuery will return an empty array.
Its because the plugin isn't loaded. jScroll is the plugin to change the scrollbars, correct? I've had numerous issues with it. I suggest wrapping it in a
$(window).load(function(){
//Call it here
})
This fixed all the issues i had with it.
Upvotes: 0
Reputation: 13222
if ($('.scroll').jScrollPane()){
$('.scroll').jScrollPane();
}
this error is prob just because an addon failed loading
Upvotes: 0
Reputation: 413737
Uhh ... no; jQuery doesn't work like that. A call to $("any selector")
will always give you back a ready-to-use (but empty) jQuery object. I don't think that's really your problem. Can you describe more about what your page is doing?
Upvotes: 0
Reputation: 7183
you can use try/catch blocks...
try
{
$('.scroll').jScrollPane();
}
catch(err)
{
//Handle or ignore errors here
}
Upvotes: 0