Search code examples
javascriptjqueryjsonfunctional-programminggetjson

more functional way of coding this block?


I am reading this color value from 3 different links and setting it as background color to some divs. What I am wondering is, if there is a better way to do it, where I won't have to repeat my self. For now its only color values but for the next step I have to read a json file which contains a lot more info. Thank you already!

$(function() {
    $.getJSON("url", function(receiveStatusPravdev01){
      var colorBox1 = receiveStatusPravdev01.status;
      $('#box1').css('background', colorBox1);
    });
    $.getJSON("url", function(receiveStatusPravdev02){
      var colorBox2 = receiveStatusPravdev02.status;
      $('#box2').css('background', colorBox2);
    });
    $.getJSON("url", function(receiveStatusPravdev03){
      var colorBox3 = receiveStatusPravdev03.status;
      $('#box3').css('background', colorBox3);
    });
});

Solution

  • You want it functional? Use a function!

    $(function() {
      function loadAndSetColor(url, selector) {
        $.getJSON(url, function(receiveStatusPravdev){
          var colorBox = receiveStatusPravdev.status;
          $(selector).css('background', colorBox);
        });
      }
      loadAndSetColor("url", '#box1');
      loadAndSetColor("url", '#box2');
      loadAndSetColor("url", '#box3');
    });