Tables carry all kinds of advanced visual gimmicks intended to make them look better. Table rendering performance is more important than ever. Generating a few labels on the fly is not a problem, but doing so with complex tables containing images overloads systems.
Tables intended for the web are best generated with the Tabulator framework. Just like all the best web design tools it's designed to streamline your workflow. This JavaScript framework contains an advanced implementation of the virtual document object programming paradigm. This means it only creates a few widgets, which it recycles as the user scrolls through your list.
In addition, the framework also provides a wide range of convenience functions. Table sizes can be adjusted to the data which is currently being displayed. Element information can be obtained from a variety of sources including REST transfers. Developers interested in creating advanced table editing experiences can also rejoice.
The product supports filtering, sorting and lets users edit table data. An optional data validation process then prevents mistakes. Given that Tabulator is completely open source, there is little reason for programming your own table rendering engine.
Want to swerve the code? Design your site with one of these top website builders, and this guide will help you get your web hosting service just right.
- Download the files that accompany this Tabulator tutorial here.
01. Load the files
Tabulator consists of a CSS stylesheet and some JavaScript. The framework’s developers have a tight relationship with the UnPKG content delivery network. Our example code fetches resources there, and furthermore declares a tag responsible for displaying the table.
<html>
<head>
<link href="https://unpkg.com/
tabulator-tables@4.3.0/dist/css/tabulator.
min.css" rel="stylesheet">
<script type="text/javascript"
src="https://unpkg.com/tabulatortables@
4.3.0/dist/js/tabulator.min.js"></
script>
</head>
<body>
<div id="example-table"></div>
</body>
</html>
02. Generate example data
Starting our demonstration with an Ajax loading process would make the code too long. Due to that, we limit ourselves to displaying static data. Create a script tag, which must be placed below the tag, and start out with an array of elements.
<div id="example-table"></div>
<script>
var tableData = [
{id:1, name:"A A", age:"24",
gender:"male", height:1, col:"red"},
{id:2, name:"B B", age:"48",
gender:"female", height:2, col:"blue"},
];
03. Initiate a code-behind class
When the array is ready, we can proceed to kicking o the rendering process. Table widgets are represented by an instance of the Tabulator class - our first task is the creation of one. Tabulator expects both field declaration and a reference to the data at hand.
var table = new
Tabulator("#example-table", {
data:tableData,
columns:[
{title:"Name",
field:"name"},
{title:"Age", field:"age"},
{title:"Gender",
field:"gender"},
{title:"Height",
field:"height"},
{title:"Favourite Color",
field:"col"},
],
});
</script>
</body>
04. Analyse the results
Open the program and feast your eyes on the table shown in the figure accompanying this step. The framework provides intelligence for sorting. This is shown in the second figure, which was created by clicking the header off the table a few times to trigger sorting.
05. Change colours during program execution
Tabulator’s constructor offers a variety of parameters. While some of these parameters are limited to simply providing static data, we can also provide event handlers. rowFormatter gets invoked once for every row generated in the table. When run, the code will show the output shown in the figure accompanying this step.
var table = new
Tabulator("#example-table", {
. . .
rowFormatter:function(row){
var data = row.getData();
if(data.col == "blue"){
row.getElement().
style.backgroundColor = "#A6A6DF";
}
if(data.col == "red"){
row.getElement().
style.backgroundColor = "#A60000";
}
},
06. Add example data
Demonstrating advanced features of the framework requires additional data. This can easily be fixed: simply return to the declaration of the table data field, and add a bunch of additional entries.
<script>
var tableData = [
{id:1, name:”A A”, age:”24”,
gender:”male”, height:1, col:”red”},
{id:2, name:”B B”, age:”48”,
gender:”female”, height:2, col:”blue”},
{id:3, name:”B B”, age:”48”,
gender:”female”, height:3, col:”white”},
{id:4, name:”B B”, age:”48”,
gender:”female”, height:4, col:”green”},
{id:5, name:”B B”, age:”48”,
gender:”female”, height:5, col:”pink”},
{id:6, name:”B B”, age:”48”,
gender:”female”, height:6, col:”xxx”},
];
07. On cell click event handlers
Add event handlers on two levels: in addition to clicking handlers for the entity of the program, you can also target specific elements of the table. Both approaches have their merits: the code accompanying this step shows how global local event handlers are set up.
var table = new Tabulator("#example-table",
{
cellClick:function(e, cell){
},
{title:"Name", field:"name",
cellClick:function(e, cell){
//e - the click event object
//cell - cell component
},
}
08. Analyse event parameters
Event handlers receive two objects with further information about the trigger. Our first test involves trying to ind out more about their contents. This is best accomplished by outputting them into the browser’s command line. Now run the example code in Firefox to see how the output presents itself.
var table = new
Tabulator("#example-table", {
cellClick:function(e, cell){
console.log(e);
console.log(cell);
},
09. Target specific cells
We can now motivate the user to pick a specific set. In principle, all we need to do is a string comparison. Tabulator makes this process a little bit more involved by not providing the value directly – instead, the object must be unwrapped before use.
var table = new Tabulator(“#example-table”,
{
cellClick:function(e, cell){
if(cell._cell.value==”A A”){
alert(“Hello, Mr A. A!”);
}
console.log(cell);
},
10. Spruce up display
Tabulator can create advanced display elements from data. This is done via helper classes known as formatters. These do exactly as you might expect and format a table. The development team provides a few right out of the box.
11. Deploy a formatter
Add its declaration to the column array. The framework will automatically detect the assignment, and will use the generated widgets to display information. In the case of our example, values are transformed into a series of stars.
columns:[
{title:”Name”, field:”name”},
{title:”Age”, field:”age”},
{title:”Gender”, field:”gender”},
{title:”Height”, field:”height”,
formatter:”star”},
{title:”Favourite Color”,
field:”col”},
],
12. Set some options
Our array contains values ranging from 1 to 6. By default, the formatter is limited to five stars. We can work around this problem by setting an attribute to modify rendering behaviour.
columns:[
{title:”Name”, field:”name”},
{title:”Age”, field:”age”},
{title:”Gender”, field:”gender”},
{title:”Height”, field:”height”,
formatter:”star”,
formatterParams:{stars:6}},
{title:”Favourite Color”,
field:”col”},
],
13. Add a button
Demonstrating some of the advanced functions of the framework requires a button with which interaction can be triggered. Return to the mark-up part of the test harness, and add the button declaration as shown. Given that our table currently does not ill to expand the screen, the button will simply appear below the table.
<body>
<div id=”example-table”></div><br>
<button onclick=”workThis()”>Apply an
action!</button>
<script>
function workThis(){
}
</script>
<script>
var tableData = [
14. Access the table instance
Accessing the table instance requires us to store it in a public variable. Given that we are programming purely on the browser, the window object is a good place for storing the value.
<script>
var tableData = [
{id:1, name:"A A", age:"24",
gender:"male", height:1, col:"red"},
. . .
});
window.myTable=table;
</script>
15. Apply a filter
Apply filters via the setFilter method. It takes three parameters - first, the ID of the column to be used. Secondarily, the comparison operator is passed in, and finally, a comparison value. In the case of our example program, click the button to make three lines disappear.
<script>
function workThis(){
window.myTable.
setFilter("height", ">", 3);
}
</script>
16. Use various filter operations
Tabulator provides a total of seven operators which can be used by passing in their string. The figure accompanying this step was taken from the product documentation. It provides a description of the operator’s function.
17. Create custom lines – I
Our final “big” task involves replacing the entire row with a bit of custom mark-up. For that, we must start out by setting up rowFormatter and providing it with a generator function.
var table = new
Tabulator(“#example-table”, {
data:tableData,
columns:[
{title:”Name”,
field:”name”}
],
height:”350px”,
layout:”fitColumns”,
resizableColumns:false,
rowFormatter:function(row){
var element = row.
getElement(),
data = row.getData(),
width = element.
offsetWidth,
rowTable, cellContents;
while(element.firstChild)
element.removeChild(element.firstChild);
18. Create custom lines - II
The second part of the routine involves creating the actual DOM snippet. Our code creates a TD tag containing the information for the current line and returns it to the framework after that.
rowTable = document.
createElement("table")
rowTable.style.width =
(width - 18) + "px";
rowTabletr = document.
createElement("tr");
cellContents = "<td>" +
data.id + "</td>";
cellContents += "<td><div><strong>Name:</
strong> " + data.name + "</div></td>"
rowTabletr.innerHTML =
cellContents;
rowTable.
appendChild(rowTabletr);
element.append(rowTable);
},
});
table.setData(tableData);
19. Modify data at runtime
Tabulator is not limited to displaying static data. The code accompanying this step illustrates four ways how information can be changed during program execution. Keep in mind that changes to the actual array are not monitored — changing the values of the array does not lead to an automatic update.
$(“#add-row”).click(function(){
table.addRow({});
});
$(“#del-row”).click(function(){
table.deleteRow(1);
});
$(“#clear”).click(function(){
table.clearData()
});
$(“#reset”).click(function(){
table.setData(tabledata);
});
20. Target framework elements
When Excel first let users apply styles, clarity improved. Being based on the concept of virtual DOM, the product generates a set of display widgets. They have a set of predefined IDs which are conveniently listed here.
21. Learn more
Tabulator’s documentation is structured in a slightly odd fashion. The gallery of examples found at here makes for a great first point of contact – click the Documentation links next to a header to be forwarded to a more detailed description of the API in question.
Got a lot of assets to store for a website build? Try the best cloud storage around..
Related articles:
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Get top Black Friday deals sent straight to your inbox: Sign up now!
We curate the best offers on creative kit and give our expert recommendations to save you time this Black Friday. Upgrade your setup for less with Creative Bloq.
Tam Hanna is a software consultant who specialises in the management of carrier and device manufacturer relationships, mobile application distribution and development, design and prototyping of process computers and sensors. He was a regular contributor to Web Designer magazine in previous years, and now occupies his time as the owner of Tamoggemon Software and Computer Software.