Isomorphic Table & Grid View Switcher In Vanilla JavaScript

Category: Javascript , Layout | December 30, 2020
Author: evoluteur
Views Total: 88 views
Official Page: Go to website
Last Update: December 30, 2020
License: MIT

Preview:

Isomorphic Table & Grid View Switcher In Vanilla JavaScript

Description:

A JavaScript library that enables you to switch between Table View and Grid View with a smooth transition effect.

Also provides a sort function that allows the user to sort data in a specific direction.

How to use it:

1. Insert the main script isomorphic-table-cards.js into the document.

<script src="js/isomorphic-table-cards.js"></script>

2. Define your data for the Table/Grid view.

var data = [
  {
    "name": "Amazonite",
    "chakra": 4,
    "spirit": "Self-determination"
  },
  {
    "name": "Amber",
    "chakra": 3,
    "spirit": "Makes carefree"
  },
  {
    "name": "Amethyst",
    "chakra": 7,
    "spirit": "Alertness, justice, inner peace",
    "body": "Good for the skin; alleviates pain, tension and lowers high blood pressure."
  },
  // ...
].sort(function(a, b){
  return (a.chakra+a.name).localeCompare(b.chakra+b.name);
});

3. Render the data in the Table/Grid view.

let itc
itc = new IsomorphicTableCards({
  // row and card dimesions
  rowHeight: 31,
  cardHeight: 94,
  cardWidth: 210,
  // item template
  itemTemplate: d => `<div class="item chakra${d.chakra}" id="${d.name}">
      <div class="c1">
        ${d.name}
      </div>
      <div class="c2">
        ${d.spirit}
      </div>
    </div>
  `,
  // sort functions
  sort: (data, key, direction) => {
    if(key=='chakra'){
      return data.sort(direction>0 ?
        (a, b) => (a.chakra+a.name).localeCompare(b.chakra+b.name)
        :
        (a, b) => ((8-a.chakra)+a.name).localeCompare((8-b.chakra)+b.name)
      )
    }else{
      return data.sort((a, b) => direction*a.name.localeCompare(b.name))
    }
  }
});
itc.render()

4. Redraw the Table/Grid view when needed (e.g. window reszie)

itc.redraw()

5. Switch between Table View and Grid View.

itc.redraw('table')
itc.redraw('cards')

6. Sort data.

itc.sort('name')
itc.sort('chakra')

Changelog:

12/30/2020

  • CSS tweak.

You Might Be Interested In:


Leave a Reply