mstef
mstef

Reputation: 1194

Conditionally passing options to a jquery function

$.fn.demo = function(options) {
    var defaults = {
        opacity: 50,
        width: '250px',
        height: '100px',
        color: 'red'
    }
  }

Is there any way to conditionally pass options to a function, like such:

$().demo({
opacity: 60,
if (div.length){
    width: '350px'
}
height: '100px'
});

Just curious what would be the best way to handle a situation where you may want to pass different options depending on circumstances. Thanks!

Upvotes: 2

Views: 5876

Answers (2)

mvbl fst
mvbl fst

Reputation: 5263

$.fn.demo = function(options) {
    var defaults = {
        opacity: 50,
        width: '250px',
        height: '100px',
        color: 'red'
    };
    options || (options = {});
    defaults = $.extend(defaults, options);
    ... function body...
}

When you use extend, it overwrites defaults and adds any arbitrary data, if it's present.

Upvotes: 4

Mihai Stancu
Mihai Stancu

Reputation: 16117

If it's simple enough you can use the ternary operation

$().demo({
    opacity: 60,
    width: div.length ? '350px' : '250px',
    height: '100px'
});

If it's more complicated you should just compose the parameter object outside of the function call.

var parameters = {
    opacity: 60,
    height: '100px'
};
if(div.length)
    parameters.width = '350px';
$().demo(parameters);

Upvotes: 12

Related Questions