How can I check if any specific jQuery user interface function is available and use another function if it is not?

I am writing a jQuery plugin and I would like my code to use the jQuery UI show(effect, [options], [speed], [callback])and functions hide(effect, [options], [speed], [callback])that allow me to show and hide elements with nice animations.

However, I would also like my plugin to correctly degrade if jQuery UI is unavailable, switching to using the basic, non-animating show()and hide()functions present in the standard jQuery API.

I need to test the show and hide the functions specifically, because even if the jQuery user interface is available, it could potentially be a custom version without the effects components included.

At first I thought I could do something like:

if(typeof myelement.show('blind', 'slow') == 'undefined')
{
    myelement.show('blind', 'slow');
}
else
{
    myelement.show();
}

But, of course, this will not work, because even if the UI is missing, show()it is still a function, it just has a different signature, so it typeofreturns objectanyway.

So what is the best way to check if jQuery UI is available for my plugin? Any help is much appreciated!

+3
source share
2 answers

You can check the effect as follows:

function hasEffect(effect) {
    return $.effects && $.effects[effect];
}

Then you can use this anywhere:

if(hasEffect('blind')) {
  myelement.show('blind', 'slow');
} else {
  myElement.show();
}
//or, you can shorten it further:
//$.fn.show.apply(myelement, hasEffect('blind') ? ['blind','slow'] : []);​

, / jQuery UI "" , , , :

$.effects.blind = function(o) { ...effecty stuff... };

, "blind" . , $.effects, $.effects.effect , jQuery UI, .

+2

Nick ; , jQuery :

$.extend({
    hasEffect: function (effect) {
        return $.effects && $.effects[effect];
    }
});

, $.hasEffect(effectname) , jQuery.

+1

Source: https://habr.com/ru/post/1750468/


All Articles