Here’s my code ( http://jsfiddle.net/nB4Hg/ ):
JQuery:
// plugin code
(function($) {
$.fn.coloredDiv = function(options) {
// defaults
var options = {
'color' : 'black'
};
$(this).css('background', options.color);
}
})(jQuery);
// use the plugin
$(function() {
$("#foo").coloredDiv({ 'color' : 'red' });
$("#bar").coloredDiv();
});
CSS:
div { width: 100px; height: 100px; margin-bottom: 10px; }
HTML:
<div id="foo"></div>
<div id="bar"></div>
Now I am trying to learn how to use options when writing plugins. In my code what I’m trying to do is specify that the first div should be colored red and the second since it has no options should be the default black. However both are black. What am I doing wrong?
Your current approach is accepting a parameter named
options, but then declaring another variable namedoptionsthat “shadows” the parameter, and thus the passed-in options never get seen by the subsequent code.Instead, you should declare your default options, then use
$.extendto overwrite those defaults with the ones passed in by the user, where applicable: