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,
          });
ctrlmaniac
  • 404
  • 4
  • 13
  • 28
  • I'am not really sure what your question is, but feel the need to give you this link: http://learn.jquery.com/plugins/basic-plugin-creation/#accepting-options – Nico O Jul 18 '14 at 17:38
  • The following question might be helpful for you: http://stackoverflow.com/questions/929776/merging-associative-arrays-javascript – Sumurai8 Jul 18 '14 at 18:04

2 Answers2

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
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.

Aaron
  • 98
  • 5
  • Does it overwrite others values when the same key is encountered? – ctrlmaniac Jul 19 '14 at 16:30
  • 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`. – Aaron Jul 19 '14 at 17:03
  • If you need it the other way around switch the two variables within $.extend. `var combinedStyles = $.extend({}, theirStyles, myStyles);` Then myStyles will overwrite theirStyles. – Aaron Jul 19 '14 at 19:46