Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send json data to jQuery.css()

I want to send json formatted data to jQuery.css() function, and i dont know how to do that. Later on, i will send more properties, this is just example of my problem.

//Sorry, this var x is actually string that i get when i print my json string
var x = {"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"}

//If i try to do something like this wont work
$("#mainImage").css(x);


//but following works
$("#mainImage").css({"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"})

It probably has to do something that jquery accepts .css( map )
A map of property-value pairs to set.

And i am trying to send single text string, can i somehow convert json to map ?

@Pekka Yes, i am sure that $("#mainImage").css(x); doesnt work.

@Felix That is what i get by calling json = JSON.stringify(data); sorry if it not json data, i am js newbie..

like image 416
grizwako Avatar asked Apr 08 '11 09:04

grizwako


2 Answers

You should parse not stringify JSON before. I tried this one It's works.

var json = '{ "display": "none" }';
var cssObject = JSON.parse(json);
$("#mainImage").css(cssObject);
like image 73
cem Avatar answered Oct 20 '22 23:10

cem


I've just tried with this code:

$(document).ready(function() {
        var x = {"background-color": "yellow"};
        $('body').css(x);
    });

And basically it works. So the problem can be in sth totally different. Maybe your img element is not there?

like image 27
Karol Avatar answered Oct 21 '22 01:10

Karol