Apply CSS Classes To Elements Depending On Numeric Values - addClassByAtt

File Size: 5.83 KB
Views Total: 350
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Apply CSS Classes To Elements Depending On Numeric Values - addClassByAtt

addClassByAtt is a super light (less than 1kb minified) jQuery plugin that applies different CSS classes elements depending on the values in a certain attribute.

Use this plugin to colorize the Text and Background colors of table cells based on the value range.

How to use it:

1. Import the minified version of the jQuery addClassByAtt plugin after jQuery.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="jquery.addClassByAtt.min.js"></script>

2. Define the min/max values and CSS classes corresponding in a JavaScript object as follows:

const classes = [
      {'class': 'class-1', 'minVal': 0, 'maxVal': 9},
      {'class': 'class-2', 'minVal': 10, 'maxVal': 59},
      {'class': 'class-3', 'minVal': 60, 'maxVal': 999},
      ...
];

3. Insert numeric values in the title attribute of your html elements.

<table>
  <thead>
    <tr>
      <th>Firstname</th>
      <th>Lastname</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td title="5">5</td>
    </tr>
    <tr>
      <td>Mary</td>
      <td>Moe</td>
      <td title="22">22</td>
    </tr>
    <tr>
      <td>July</td>
      <td>Dooley</td>
      <td title="65">65</td>
    </tr>
  </tbody>
</table>

4. Initialize the plugin and done.

$('table td').addClassByAtt({
  'options': classes
});

5. Override the default attribute.

$('table td').addClassByAtt({
  'options': classes,
  'attribute': 'title'
});

This awesome jQuery plugin is developed by gar-cad. For more Advanced Usages, please check the demo page or visit the official website.