0

I'm programming a plugin and I need users to customize it the function and not in an external CSS. I have an object with some default style in it that can be overriden by the users. BUT I need to set the width and the marginLeft according to other functions. So in my experience I would add the default style (given by the user) by passing it in the css method BUT I can't add more strings if not by adding a new line of .css() method.

Is there a better way to write this code?

var style: {
    'position': 'fixed',
    'top': 0,
    'left': 0,
    'bottom': 0
};

$( 'div' ).css( style )
          .css({
              width: 300,
              marginLeft: -300,
          });
2

2 Answers 2

2

You can extend the defaults with the settings passed to the plugin

var styles = $.extend(
    {  // defaults
        position : 'fixed',
        top      : 0,
        left     : 0,
        bottom   : 0
    },
    settings, // settings object passed in
    {
        width      : 300, // always overwrites the above
        marginLeft : -300,
    }
)

$('div').css(styles);

As you'll notice, the object passed last will always overwrite the previous ones if the same key exists.
This is generally how plugins extend default settings with objects passed in by users, it's not really easier to write, but it is more extendable in the way the objects overwrite each others values when the same key is encountered.

Sign up to request clarification or add additional context in comments.

Comments

1

Using .extend() it will merge the contents of two or more objects together into the first object.

var theirStyles = {
   'position' : 'absolute',
   'top' : '0',
   'left' : '0',
   'bottom' : '0',
   'margin' : '0',
   'font-size' : '30px'
};

var myStyles = {
   'width' : '300px',
   'margin-left' : '-300px'
};


var combinedStyles = $.extend({},  myStyles, theirStyles);


$('div').css(combinedStyles);

Hope that helps!

The FIDDLE.

3 Comments

Does it overwrite others values when the same key is encountered?
Yes. If you look at the jsfiddle (using Chrome Developer Tools) and inspect the word 'Work' you'll notice that width: 300px is there but margin-left:-300px was replaced with margin:0.
If you need it the other way around switch the two variables within $.extend. var combinedStyles = $.extend({}, theirStyles, myStyles); Then myStyles will overwrite theirStyles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.