Sam Willis Sam Willis - 6 months ago 8
jQuery Question

jQuery plugin option as a css property

I am creating a plugin that accepts options when it is called. However, I want one of the options to also double up as a css property (position)

var settings = $.extend({
position : 'right',
size : '300px',
speed : '1000ms'
}, options );

if (settings.position == 'left' || settings.position == 'right') {
return this.css({
width: settings.size,
height: '100%',
settings.position: '-' + settings.size
});
}


I want the
settings.position: '-' + settings.size
to effectively output:
right: -300px
.

Thanks

Answer

Try

var css = {
    width: settings.size,
    height: '100%'
};

css[settings.position] = '-' + settings.size;

return this.css(css);

This way the interpreter will evaluate settings.position into a string first, causing the expression to become css['left'] = ...

Comments