6

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..

2
  • 3
    Strange. $("#mainImage").css(x); should work. Are you 100% sure it doesn't? Commented Apr 8, 2011 at 9:44
  • 2
    x is not JSON. It is a JavaScript object. Commented Apr 8, 2011 at 9:44

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I think you can parse with jQuery.parseJSON() to add some more backwards compatibility; JSON.parse() is available only in modern browsers
2

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?

1 Comment

Yeah, its there, i should have parsed it first, that is why it didnt work.
0

http://jsfiddle.net/A4azg/

var cssObj = {
      'background-color' : '#ddd',
      'font-weight' : '',
      'color' : 'red',
      "transform":"rotate(30deg)",
      "-o-transform":"rotate(30deg)",
      "-webkit-transform":"rotate(30deg)"
    }
$("#mainImage").css(cssObj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.