Dynamically creating tables with clusterize.js

Quite often you need to present dynamic tables in Html Service. They can be laborious to code and can get sluggish if large. Clusterize.js gives some great capabilities to help with that.  

Imagine you have this spreadsheet data to tabularize in a sidebar.
var data = [
  ['france', 100],
  ['germany', 20],
  ['italy', 300],
  ['spain', 20],
  ['uk', 30],
  ['lithuania', 310],
  ['estonia', 32],
  ['switzerland', 13],
  ['romania', 89],
  ['portugal', 42],
  ['bulgaria', 12],
  ['ukraine', 031],
  ['sweden', 45],
  ['norway', 80],
  ['denmark', 200],
  ['belgium', 100]
];

Clusterize.js markup. 

There are quite a few options for how to do this, but probably the simplest is this
<div class="clusterize">
  <table>
    <thead>
      <tr>
        <th>country</th>
        <th>amount</th>
      </tr>
    </thead>
  </table>
  <div id="scrollArea" class="clusterize-scroll">
    <table>
      <tbody id="contentArea" class="clusterize-content">
        <tr class="clusterize-no-data">
          <td>Loading data…</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>


Clusterize.js JavaScript.

A simple mapping of the data provides the input data table and its maarkup for optimization to clusterize.js

var clusterize = new Clusterize({
  rows: data.map(function(row) {
  return "<tr>" +
    row.map(function(col) {
      return '<td>' + col + '</td>';
    }).join(" ") +
   "</tr>"
  }),
  scrollId: 'scrollArea',
  contentId: 'contentArea'
});

Cdn

You'll need these
https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.16.1/clusterize.min.css
https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.16.1/clusterize.min.js

Demo


You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.






For more like this, see Google Apps Scripts snippets. Why not join our forumfollow the blog or follow me on twitter to ensure you get updates when they are available. 



Comments