How to create a sortable HTML table with JavaScript


1. Inserting content with HTML

The <table> tag is the semantic HTML tag used to display data on a web page. We will put ours <table> tag inside a div table-container which will allow us to include some responsive styles in the CSS.

Our table will contain the table header, thead and contents of the table, tbody tag. In the header of our table, we will include buttons in each th cell that will be used to manage the sorting functionality. The cells for the table content will be added with JavaScript using the data from our JSON response.

2. Making a responsive table with CSS

One of the most common problems in using HTML tables is the lack of responsiveness. The table may have a cell overlap problem or go beyond the boundaries of the entire page.

We can get rid of these problems by placing the table in a full page width table container with an overflow scroll property. In this way, the table is always as wide as the entire page and there is no need to shrink the cells thanks to the sliding overflow. We will also include minimum width properties in table cells to avoid text wrapping.

table that flows beyond the boundaries of the pagetable that flows beyond the boundaries of the page
Overflowing table beyond the window without squeezing

This is the CSS needed to make our table scrollable:

We can then add the rest of our style:

3. Inserting JSON data into an HTML table

For this example, we will work with a mock parsed JSON response. Here’s what our data looks like:

We will put the data inside ours <tbody id="table-content"> tag to target that element in JavaScript;

The content of the row will be based on each object within ours response.pokedata. Let’s define a function to create a new row based on the object data:

In this function we use the Object.keys() method to get the keys of the object as an array. Here’s what the return value looks like:

Keys.object (obj) (9) ['name', 'type', 'hp', 'attack', 'defense', 'spAttack', 'spDefense', 'speed', 'total']Keys.object (obj) (9) ['name', 'type', 'hp', 'attack', 'defense', 'spAttack', 'spDefense', 'speed', 'total']Keys.object (obj) (9) ['name', 'type', 'hp', 'attack', 'defense', 'spAttack', 'spDefense', 'speed', 'total']
Object.keys () returns an array containing the keys of the object

Once we have the object’s key array, we loop through each key using the .map() method. The map method executes the function we passed to it on each element in the array.

In this map function, we create a new cell for each element in the array and set the innerHTML cell as the corresponding object key value.

Object mapping using the key arrayObject mapping using the key arrayObject mapping using the key array
Object mapping using the key array

Finally, we add the cell we created to the row defined at the start of the function using the .appendChild() method.

Now that we have our line creation function, we will define a function to iterate over the response.pokedata array and add each new row to ours tableContent element.

We will pass ours getTableContent function in an event listener so that content is added to the table once the page is loaded.

4. Sorting data with JavaScript

Now that we’ve created our table, let’s add sorting functionality. In our HTML, we included the buttons in the header cells that had the object keys as the ID. Let’s now target those buttons:

We want to manage the sorting of data based on the button clicked and also include a function that toggles the sort direction (ascending or descending) when the button is clicked.

We can use the .sort() method to manage the sorting of data in our response.pokedata Vector. The sorting method accepts a function that compares two different parameters and sorts them based on the function’s response:







compareFunction(a, b) return value sorting
> 0 to sort a after b
<0 to sort a Before b
=== 0 keep the original order of a And b

Source: MDN

Another thing to note about the sorting method is that it changes the original array it operates on. This means it changes the value of our original array.

Mutation of the array when using .sort ()

We can avoid mutating our original array by using spread syntax […]

Avoid array mutation by using diffusion syntax

Now we can create our sorting function. Here’s what the logic for our sort function will look like:

  1. Clears the content in the tableContent element
  2. Sorts the data according to the selected parameter and direction
  3. Add the sorted data to our tableContent using the file getTableContent function

Our sort function accepts three parameters:

  • data: the array to be ordered
  • param: the value used to sort the array
  • direction: sorts the array in ascending or descending order. The default value of the parameter is set to “asc”.

We clear the content in our tableContent element by setting innerHTML to an empty string. We therefore use the .sort() method e direction parameter to determine how the data should be sorted. We reverse the comparison function to sort in descending order. Using the compare function in this way allows us to sort the data regardless of the type value (string, integer, float etc.)

Finally, we pass the sortedData as a new value in the content of our table.

We will now pass our sort function into a click event listener for our table buttons and also handle the toggle of the sort direction.

In this function, we manage the switching by setting a data-dir attribute on our buttons to determine the sort direction. We will also update our CSS to display an icon next to the button depending on the sort direction:

We don’t want icons to appear on all previously clicked buttons, so we’ll define a resetButtons function that removes the data-dir attribute on any button other than the button clicked.

We will pass that function to our button event listener to revert to the previous buttons each time a new button is clicked

Conclusion

And with that, we’re done! We created a sortable table using vanilla JavaScript only!



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *