jqueryjsontemplate-literalsjson-valuedynamic-class

Adding Classes to Dynamic JSON Values


I have a list of dynamic users with various occupations in a variety of industries, depending on their industry (health, education, construction, science, etc), I would like to add a color badge that is displayed dynamically depending on industry the user is in, in order quickly differentiate the users at a quick glance. The code works well when targeting the text values in a hard coded html environment but seems to break down when trying to reference the text values loaded from dynamic JSON.

I have included the code below.

Any help would be greatly appreciated!

Thanks, Steve.

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function (populateUsers) {

    //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL CARD
    var userCard = populateUsers.reduce((acc, {id, name, username, email, phone, company, industry}) =>
            acc += `
            <div class='col col-4 align-items-stretch strain-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h2 class="title">${name}</h2>
                        <h6 class="title">${username}</h6>
                        <h6 class="title">${email}</h6>
                        <h6 class="title">${phone}</h6>
                        <h6 class="title">${company}</h6>
                        <h6 class="industry-type title">${industry}</h6>
                    </div>
                </div>
            </div>`
    , ``);
    $('#user-grid').append(userCard)
});

//THIS IS THE CODE TO TARGET INDUSTRY TYPE CLASS
var $industryType = $('.industry-type');

//THIS IS THE CODE TO ADD INDUSTRY BADGE BASED ON INDUSTRY TYPE TEXT VALUE
$industryType.each(function() {
    var $this = jQuery(this);
    if ($this.text().trim() == 'Health') {
        $this.addClass('health-badge');
    } else if ($this.text().trim() == 'Education') {
        $this.addClass('education-badge');
    } else if ($this.text().trim() == 'Construction') {
        $this.addClass('construction-badge');
    } else if ($this.text().trim() == 'Science') {
        $this.addClass('science-badge');
    }
});
.health-badge {
    background-color: purple;
    color: green;
    height: 80px;
    width: 80px;
}
.science-badge {
    background-color: black;
    color: yellow;
    height: 80px;
    width: 80px;
}
.construction-badge {
    background-color: blue;
    color: white;
    height: 80px;
    width: 80px;
}
.education-badge {
    background-color: orangered;
    color: black;
    height: 80px;
    width: 80px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

    
<body>

<!-- USER GRID -->
<div id="user-grid" class="row container fluid-container"></div>   

</body>


Solution

  • Add the class when adding the new elements.

    You can use an object to hold the mapping between industry names and the corresponding badge classes, so you don't need all those if statements and can use this for both the static and dynamic code.

    const industry_class = {
      "Health": "health-badge",
      "Education": "education-badge",
      "Construction": "construction-badge",
      "Science": "science-badge"
    };
    
    //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
    var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'
    
    //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
    $.getJSON(userJSON, function(populateUsers) {
    
      //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL CARD
      var userCard = populateUsers.map(({id, name, username, email, phone, company, industry}) => {
        let cls = industry_class[industry.trim()] || "";
        return `
                <div class='col col-4 align-items-stretch strain-container'>
                    <div id="${id}" class="card user-card">
                        <div class="card-body">
                            <h2 class="title">${name}</h2>
                            <h6 class="title">${username}</h6>
                            <h6 class="title">${email}</h6>
                            <h6 class="title">${phone}</h6>
                            <h6 class="title">${company}</h6>
                            <h6 class="industry-type title ${cls}">${industry}</h6>
                        </div>
                    </div>
                </div>`;
      }).join("");
      $('#user-grid').append(userCard)
    });
    
    var $industryType = $('.industry-type');
    
    $industryType.each(function() {
      var $this = jQuery(this);
      let industry = $this.text().trim();
      if (industry in industry_class) {
        $this.addClass(industry_class[industry]);
      }
    
    });
    .health-badge {
      background-color: purple;
      color: green;
      height: 80px;
      width: 80px;
    }
    
    .science-badge {
      background-color: black;
      color: yellow;
      height: 80px;
      width: 80px;
    }
    
    .construction-badge {
      background-color: blue;
      color: white;
      height: 80px;
      width: 80px;
    }
    
    .education-badge {
      background-color: orangered;
      color: black;
      height: 80px;
      width: 80px;
    }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    
    
    <body>
    
      <!-- USER GRID -->
      <div id="user-grid" class="row container fluid-container"></div>
    
    </body>