Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript [object Object] to string

I'll start with a little background.

So what I'm trying to do is grabbing the "style" attribute from an element, and the eventual plan is to output it to a text box (the styling is dynamic). With this I'm creating some css prefixing, due to the fact that I'm only grabing computed styles.

With that, I have a variable with a bunch of css properties as seen here:

compcss = {
                'font-size': fsize,
                'padding': tpadd,

                '-webkit-border-radius': brad,
                '-moz-border-radius': brad,
                '-o-border-radius': brad,
                '-ms-border-radius': brad,
                'border-radius': brad,

                'background': bground,
                'background-m': bgmoz,
                'background-o': bgop,
                'background-i': bgie,
                'color': 'white',
                'text-shadow': '0 -1px 0 rgba(0, 0, 0, 0.25)',
                'text-decoration': 'none',
                'border': '1px solid rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25)',

            };

Normally fsize, tpadd, brad, and bground are filled with

document.defaultView.getComputedStyle(cssStr[0], "")[style]

but for the following jsbin I put in static numbers.

This returns as [object Object] when logged or put into the text box, which is to be expected. However, I wish to get this object outputting as a string in the form:

font-size: Xpx;
padding: Ypx;
-webkit-border-radius: Zpx;

and so on, I've tried JSON.stringify(compcss), but that returns as:

"font-fize":"Xpx","padding":"Ypx","-webkit-border-radius":"Zpx"

all the way down the line.

What is the best way to get this to output the way I want? Let me know if anything needs clarifying. Is there a better way of going about this?

here's a jsbin for example: http://jsbin.com/opiwuy/2/edit

Both Vanilla Javascript and JQuery are fine.

Thanks!

like image 625
MoDFoX Avatar asked Jun 01 '12 17:06

MoDFoX


2 Answers

  var value = '';
  $.each(compcss, function(key, val) {
    value += key + ' : ' + val + ';' +'\n';
  });
  $('#css').val(value);

DEMO

You can also do

$('#css').val(function() {
    var value = '';
    $.each(compcss, function(key, val) {
      value += key + ' : ' + val + ';' + '\n';
    });
    return value;
});

DEMO

like image 161
thecodeparadox Avatar answered Sep 28 '22 00:09

thecodeparadox


something like this would probably suit your needs:

function cssStringify(myObject) {
    var result = "";
    var stringObjs = JSON.stringify(myObject).split(",");
    $.each(stringObjs, function(val) {
        var pair = val.split(":");
        result = result + pair[0] + ":" + pair[1] + ";\n";
    });
    return result;
}
like image 24
robbymurphy Avatar answered Sep 28 '22 01:09

robbymurphy