mohamed saed mohamed saed -4 years ago 92
CSS Question

How to load specific data as colors from JSON file

hi guys am trying to load data from JSON file and i wanna use it as background for each block that get fitch

so the block is a box and each box have 4 small boxs and i wanna target these 4 boxs and changes there background color based on the JSON file data

here is the JSON format i use

[
{
"name" : "color1" ,
"box1" : "#7f6ded" ,
"box2" : "#343434" ,
"box3" : "#ffffff" ,
"box4" : "#858585"
} ,
{
"name" : "color2" ,
"box1" : "#58c9b9" ,
"box2" : "#343434" ,
"box3" : "#ffffff" ,
"box4" : "#9dc8c8"
}
]


and the here is the calling jq

$(function () {

// start calling colors
$.getJSON( "js/colors.json", function( data ) {

// console.log(data[1].box1);
var output = "";
var output2 = "";
for (var i = 0; i < data.length; i++) {

output +=
"<div class=" + "col-md-4" + ">" +
"<div class=" + "co-palet" + ">" +
"<div class=" + "box box-1" + "></div>" +
"<div class=" + "box box-2" + "></div>" +
"<div class=" + "box box-3" + "></div>" +
"<div class=" + "box box-4" + "></div>"
+ "</div>" + "</div>"

$('#myColors').html(output);
};

});
// end calling colors



});


and i output into

<div id="myColors"></div>


any help would be appreciated :)

Answer Source

Just add a style attribute to your boxes.

$.getJSON( "js/colors.json", function( data ) {

  var output = "";
  for (var i = 0; i < data.length; i++) {

    output +=
            "<div class=\"col-md-4\">" +
            "<div class=\"co-palet\">" +
            "<div class=\"box box-1\" style=\"background-color:" + data[i].box1 + "\"></div>" +
            "<div class=\"box box-2\" style=\"background-color:" + data[i].box2 + "\"></div>" +
            "<div class=\"box box-3\" style=\"background-color:" + data[i].box3 + "\"></div>" +
            "<div class=\"box box-4\" style=\"background-color:" + data[i].box4 + "\"></div>"
            + "</div>" + "</div>";

  };
  $('#myColors').html(output); //move this outside the loop so it isn't overwritten every time
});

Also, make sure to properly escape your quotes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download