$.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!
$.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!
Share Improve this question asked Jun 27, 2012 at 15:48 mstefmstef 1,1941 gold badge13 silver badges37 bronze badges 02 Answers
Reset to default 12If it's simple enough you can use the ternary operation
$().demo({
opacity: 60,
width: div.length ? '350px' : '250px',
height: '100px'
});
If it's more plicated you should just pose the parameter object outside of the function call.
var parameters = {
opacity: 60,
height: '100px'
};
if(div.length)
parameters.width = '350px';
$().demo(parameters);
$.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.