0

So I am trying to write a jQuery plugin and I have three values that I would like to set the defaults for one is a simple numeric value the others can be set if the user wants, but if they do not set them they need to have a default value of whatever the first is set.

Here is a longer version of what I want

config.duration = 350;
config.closeDuration = closeDuration OR duration;
config.openDuration = openDuration OR duration;

Basically if they are not set default back to whatever the duration value is. Even if the value has been set by the user. (eg. duration = 500)

I am just wondering if there is anyway to streamline this?

jQuery.fn.lighthouse = function(settings) {
    var config = {
            containerSelector: 'a',
            childSelector: 'span',
            closeSelector: '.close',
            duration: 350,
            openDuration: config.duration,
            closeDuration: config.duration,
            secondaryDuration: 100,
            background: 'rgb(230, 230, 230)',
            backgroundOpacity: '0.7'
        };

    if (settings){
        config = $.extend(config, settings);
    }
}
godismyjudge95
  • 922
  • 1
  • 9
  • 15

1 Answers1

2

By setting the optional values to null, one can then use an inline if statement to determine the value of the setting. Here is a combination of both Karl-André Gagnon and charlietfl answers:

jQuery.fn.lighthouse = function(settings) {
    var config = {
        containerSelector: 'a',
        childSelector: 'span',
        closeSelector: '.close',
        duration: 350,
        openDuration: null,
        closeDuration: null,
        secondaryDuration: 100,
        background: 'rgb(230, 230, 230)',
        backgroundOpacity: '0.7'
    };

    if (settings){
        config = $.extend(config, settings);
    }

    config.openDuration = config.openDuration || config.duration;
    config.closeDuration = config.closeDuration || config.duration;
}
godismyjudge95
  • 922
  • 1
  • 9
  • 15