Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build JavaScript Object to use with jQuery .css() (what about duplicate keys?)

I use jQuery's .css() method to apply styles to an element. I do this like so:

var cssObj = {
    'background-color' : '#000',
    'background-image': '-webkit-linear-gradient(top,#000,#fff)',
    'background-image': 'linear-gradient(top,#000,#fff)'
};

$(".element").css(cssObj);

The problem with this is that obviously I use duplicate keys in the object, which is not cool.

How can I solve this problem? I need to pass the CSS params with duplicate names to address most browsers.

like image 837
j7nn7k Avatar asked Dec 10 '11 15:12

j7nn7k


2 Answers

Having multiple keys with the same name is not valid, and will generate an error in strict mode.

Create a function/plugin which applies the properties of your cssObj. If a string-string pair is found, set a CSS property with the desired value.
If an array is found, loop through it, and update the property with each value. If an invalid value is found, it's ignored.

DEMO: http://jsfiddle.net/RgfQw/

// Created a plugin for project portability
(function($){
    $.fn.cssMap = function(map){
        var $element = this;
        $.each(map, function(property, value){
            if (value instanceof Array) {
                for(var i=0, len=value.length; i<len; i++) {
                    $element.css(property, value[i]);
                }
            } else {
                $element.css(property, value);
            }
        });
    }
})(jQuery);

// Usage:
var cssObj = {
    'background-color': '#000',
    'background-image': ['-webkit-linear-gradient(top,#000,#fff)',
                         'linear-gradient(top,#000,#fff)']
};
$(".element").cssMap(cssObj);
like image 193
Rob W Avatar answered Oct 14 '22 13:10

Rob W


My advice would be to put your CSS into your stylesheet in it's own class, and simply add that class to your element instead. The browser itself will determine which of the background-image properties it supports, and will therefore only render that one.

CSS

.gradient-bg {
    background-color: #000;
    background-image: -webkit-linear-gradient(top, #000, #fff);
    background-image: linear-gradient(top, #000, #fff)
}

jQuery

$(".element").addClass("gradient-bg");
like image 38
Rory McCrossan Avatar answered Oct 14 '22 14:10

Rory McCrossan