Create a JavaScript object for use with jQuery.css () (what about duplicate keys?)

I am using the jQuery .css() method to apply styles to an element. I do it like this:

 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 is that, obviously, I am using duplicate keys in the object, which is not cool.

How can I solve this problem? I need to pass CSS parameters with duplicate names to appeal to most browsers.

+7
source share
5 answers

Multiple keys with the same name are not valid and will cause an error in strict mode.

Create a function / plugin that applies the properties of your cssObj . If a string string string is found, set the CSS property with the desired value.
If an array is found, skip it and update the property with each value. If an invalid value is found, it is 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); 
+11
source

My advice would be to put your CSS in your stylesheet in your own class and just add that class to your element. The browser itself will determine which of the background-image properties it supports, and therefore it will display only 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"); 
+2
source

You need to create a custom $.cssHooks ( more ) that determines which one is the correct form by doing various tests --- or you can just use the css class with $.fn.addClass .

0
source

For most properties, there is a cssHooks repository for github. Writing your own hook is difficult, a lot of things on the edge.

https://github.com/brandonaaron/jquery-cssHooks

For the gradient of the background image you will need:

https://github.com/brandonaaron/jquery-cssHooks/blob/master/gradients.js

0
source

It sounds like you mean that the .css() method works like CSS attributes in a .css file. I do not think so. But here are a few alternatives:

  • Use browser sniffing (why not? Are you already doing CSS with multiple browsers with vendor prefixes)

  • Use the actual stylesheet linked as a <link />

  • Create a <style> and add rules to it dynamically.

  • Use style attribute: $('#my').attr('style', 'background: ...; bakground: ...; border-radius: ...; -moz-border-radius: ...;');

-one
source

All Articles