How to EASILY Sort HTML Tables with CSS & JavaScript - Web Development Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys hey going so in today's video I'll be showing you how to sort your HTML tables using javascript so we're going to be using a very simple technique using the built-in array sort method and it's going to work perfectly fine for text and numbers as the values inside the columns however it is extendable which means that if you want to add your own custom logic into the sorting then it's going to be very easy to do so it also seems to perform really well I don't see any performance drop-offs even when testing with a recent generation iPad and over three hundred and fifty rows in the table it still seems to work almost instantly but anyway right here is the example as we can see if I was to click on a column header it's gonna sort by that header or by that column and it's very straightforward as you might expect so as you might expect in the way it works okay so let's go inside this head right here and begin from scratch to create this table sorting so inside the index.html file for that tab it looks something like this so first let's create a new source directory and inside here we're going to be including a new CSS file it's going to be called a table sort dot CSS and this of course is going to be holding all of these CSS styles for the table sorting so things like are these symbols for the up and down and also the background color they get supplied for the currently selected column okay we can also create a new table soft dot J's file and this one of course is going to hold the JavaScript for the table of sorting we can then include those two files inside here so link for CSS at source and then table saw that CSS and do the same thing down here for the JavaScript we're gonna be including source and then table sort Jaya so now we are ready to move on to the HTML for the table sorting so firstly let's actually create a table to perform the sorting on so let's a new HTML table right here with a class of table and a second class of table - sortable so this first class here the table class is not important to this tutorial it is simply there just to make my tables look nicer for the video however this table - suitable class right here is important and basically we're just saying that the table is going to be flagged as being sortable so it supports sorting okay inside here we can create a new table head element and inside here we can of course specify a row to contain each one of our column headers we can just use the same data as I did for the example so we can say rank then I can say name then age and then occupation okay cool so now for the table body I'm just gonna create a new table row here and I might just copy and paste the data which I used in the previous example so I'm gonna copy this from here and then paste it on the second screen right there okay so as we can see I have four rows of data so now saving this and refreshing and gives us something like this so now we can move on to doing the JavaScript - of course I sort the tables so inside the table sort J's file we're going to be doing this by creating a function and this function is going to simply sort the table and it's going to be taken in three parameters the first one is going to be the actual HTML table itself the second one is going to be the index of the column to sort and the third one is gonna be whether or not we're gonna sort ascending or descending okay so let's create that function right now we're gonna be calling that function soft table by column and like I said it's gonna be taking in three parameters okay more arguments it's gonna be our table as the first one the second one is gonna be column so column index and the last one is gonna be ascending or descending I'm also going to be providing a d5 value for this parameter and that is going to be true so if I default we're gonna be ascending so we're gonna be sorting by ascending by default okay I might just put some J stock up here in order to document this function so we can say first here for the first parameter we're gonna be passing in a HTML at table elements as the datatype for that parameter I'm just gonna say here as a description the table to sort for the second one here it's going to be a number and this will be the the index of the column to sort okay and the last one here of course it's gonna be a boolean and for this one we're just gonna say determines if the sorting will be in ascending order so of course passing in false to this argument here is gonna sort it by descending instead of ascending and for the description here we can simply just say sorts a HTML table okay so now inside the function we can firstly just grab hold of the table body element because remember we're gonna be passing in an actual HTML table element into here so first let's make a new constant called T body which is equal to table t bodies at index 0 so this is unfortunately only gonna work when you have a single table body element inside your table you can definitely modify it and make it work for mod support C bodies but for simplicity and to cover most scenarios I'm gonna be having a single T body or less support for only a single T body so now we can make a new second constant and this one's going to be called rows equal to array from and we're gonna be saying here T body query selector all we're gonna pass in here TR okay so one second sorry so gonna pass in here TR and basically here we're just selecting every single table row element so every single one of these that I inside the tea body okay and by using the array dot from it guarantees that we're going to be getting we're going to be getting an array of tea ours instead of the node list and that's going to be important for doing the actual sorting okay so now I do want to create one more constant just up here and this one's going to be called Direction modifier so dir modifier and we're going to say here if we have provided ascending equals true in the parameter then we're going to say one otherwise we're gonna say negative one I'll get into more of what this is doing a bit later on when we actually get to these sewing but for now let's keep it right there so now we're going to be actually sorting the rows so we can just say down here sort each row okay and then we're gonna say it Const sorted rows is equal to the current row so the array of table row elements we're gonna say rows dot sort and then inside here for the compare function we're going to be of course accepting the a and the B so essentially right here with the a and B where a and B both refer to a single table row element and basically you're going to be returning negative one or one from this function to determine the way it's going to be sorted so inside here inside this function we're going to be grabbing the text content for each one of our table rows at the specified column index okay so I do want to just go inside here and console dot log just for now I'm gonna be logging out both a and B okay just for now right and then down here I'm gonna say sought table by column I'm gonna be calling their function okay now we're gonna be of course passing through this table right here so let's say document period selector and passing here the the table element right there and then we're going to say for example this just to one so now for these second column so basically we are passing in this table right here to the sort table by column function so now let's save this and then refresh the browser in the console as we can see we get each one of those table row elements logged out to the to the console right so that is what we are working with so now with each one of these table row elements we're going to be getting the tables cell at the specified index so back inside here let's create a constant called a Col Tex oak table row a column text is equal to a dot query selector okay we're gonna be passing in here using es6 template strings okay so using the backticks right there for this string we're gonna say TD empty hate - child just like that okay then we're gonna say dot text content and then got shrimp okay so now inside this nth child what so called CSS pseudo pseudo class I believe or pseudo selector I'm not entirely sure I forgot um by inside year we're gonna be passing in column plus one okay so basically we are saying get the table data or the table sale element at the index which we passed in okay let's do the same thing now for the be Col text instead doing be or putting P so putting B inside here so that's just in our console dot log both the ecole text and the Bicol text okay save this and refresh and now we get all of the data right there for the name column of course for each row okay cool amps now we actually have the data we can of course simply compare them and then say ascending or descending so we're going to say return from this function we're going to say if a cult X is greater than B context then we're going to say this right here we're going to say one x direction modifier otherwise we are going to say negative one times the direction modifier now let's just console.log these sordid rows okay let's now save this and then refresh and as we can see right here we now get of course the for table rows and we can see that by sorting by the name column Andrey this first guy here he is first in the list the second we expect to be done as we can see and then John and then Rebecca's as we can see our sorting our technique is working perfectly fine and now let's go back inside here I just changed this direction and let's just say false to make it descending saving this and refreshing now gives us a result where we have Rebecca first and then we have done and then DOM and then Andre so it's working perfectly fine so now we simply just need to insert or reinsert those rows into the table so let's say right here remove all existing tears from the table and we're gonna be saying while tea body dot first child so while there is the first child in the tea body so a single table row element we're gonna say tea body you've got the remove child and I'm gonna pass in here tea body dot first child also just be careful with the with the capitalization of the tea body constant you may want to use all lower case if it makes it easier but anyway essentially here we're saying that while there is a first child or while there is a first a single table element inside the tea body then we're going to be just consecutively or continually removing each one until we reach the end so this is basically just clearing out each table row from the table body and then down here we can just say react their newly sordid rows okay and for this we're gonna simply say T buddy dot append I'm gonna pass in here I'm just gonna say sorted rows so basically this is going to be passing in each one of these sorted rows into the T body dot append method and basically it just means that each one of these rows are gonna be passed in and appended to the T body so now let's save this and then refresh the browser and as we can see now the sorting is complete and of course seems to be working perfectly fine we have Rebecca first for the descending order they're done then dumb and then Andre of course let's go inside here and make this true for ascending try again and we now yet Andre Dom John and Rebecca and of course as we can see the whole table row element has been sorted as we expect so the ranking is obviously in the wrong order and of course so is a few other things but that's basically how they're going to be doing it it's very straightforward so now that we have the logic correct we're gonna be essentially just remembering which direction that the that each column or this particular column right here was actually a sorted in so we're gonna say here remember how the column is currently sorted so of course if looking at the name column right now of course currently the name column is sorted ascending so we want to actually remember this and that's gonna help with toggling back and forth between ascending and descending okay so back inside here let's just say table dot query selector all we're gonna be selecting each one of the table head elements and we're gonna say for each one of those table head elements we're gonna say th I'm gonna say th class list dot remove and then pass in here th sort a say SC and then at th sort and then des see and this will make more sense very shortly but I do under to go down here now and say table into a query selector and pass in here th and then n n th child once again selecting the table header at this time at the specified index and we're gonna say inside here column plus one we're gonna say dot class list and we're going to say toggle then I'm going to say th sort a SC and then passing the a SC parameter from up here this will make more sense very shortly we can now just do the same thing and say th sort des RDS si so essentially and here also we're going to put in a an exclamation mark to flip that boolean so essentially we are saying that if we passed in ascending then we're going to be adding the th sort a SC class to the table header so of course this one right here in this example so the name table header we're going to be adding that class right there to that header if we passed in descending then we're going to be putting the de SC class instead on the table header and of course up here we're going to essentially just clear out all of the current sorting on the table to remove each one of these classes which may have previously been inserted from these two lines right here so now saving this and then refreshing and then clicking on the inspector here we can see that this this table header has a class of th sought ASC and of course if I was to make this a false okay try again refresh and now we get th sort des see of course short for descending so that's working perfectly fine and that is all for this function right here so let's just minimize this function and then actually apply the table sorting to every single table which appears on page loads so for this we're gonna say document but query selector or and passing in here dot table sortable and then th so basically we're going to be selecting every single table our table header elements that is within a table that is sortable okay I'm gonna say dot for each okay we can just say header cell right here or even th is going to work perfectly fine okay and inside here we're gonna just say head up so dot add event listener I'm gonna pass in click so basically when the table header gets clicked on we're gonna run this function inside here now and this function is gonna say Con stable element is equal to header cell dot Heron elements dot parent element dot parent element okay so basically this table element needs to refer to this table right here if we begin with the th as we are then going up the parent once twice and three times is going to give us the table element itself so that is why I'm doing parent to parent parent okay we can then say Const header index is equal to array dot prototype dot index of okay we're gonna say dot call and then pass in here head out soul dot parent element and dot children and then we're gonna pass in header cell so basically we're making use of the index of function which is found typically on arrays and we are instead calling it on on each one of the children elements in the header so essentially when it says dot children this refers to an array like data structure of each one of these table header elements right here and basically we are saying find the index of the header cell which we clicked on of course running this function right here is going to give us a value of one for the name table header if we click on the name ok so 0 1 2 3 and that's basically how that's gonna work so now we have the table elements we have the header index the last one here is going to be the ASC ascending or descending so for this one it's gonna be slightly more complicated we're just gonna say Const current is ascending is equal to header cell dot class list dot contains then we're gonna say th - sort - ASC so we're just saying that the that the column is currently sorted ascending if it contains the THS or ASC class which we of course added inside here if we did choose to use ascending okay so that is how we get that value so now it is as simple as just saying sought table by column we're going to call the function letter parts in the table elements and also of course the header index and then we're gonna say nuts current is ascending so we're gonna be flipping this boolean right here to simply make make make it go the other way around from ascending to descending and then ascending descending etc okay so that is all it needs so now saving this and then refreshing the browser it should now work perfectly fine so pressing on name for example is going to flip the names each time and of course it's gonna work for every single column now that we actually used the add event listener for the click on each one of our table header elements so now the last part of this video is gonna be doing the CSS to make it look like this so it's gonna be very easy so inside these CSS we can firstly just target the table - sortable class I'm gonna say each one of those table header elements we're gonna say cursor and make this pointer we can then say dot table sortable then we're gonna say dot th soart - a SC then column colon after so basically this is going to be selecting the table header element which is currently sorted once again using the class which we specified earlier inside here okay so if the table here is being sorted ascending then we're gonna say contents I'm gonna be saying backslash 2 5 and then B 4 so this one here is gonna be the Unicode representation of I believe it is going to be the triangle which starts small and then gets bigger for ascending okay we can do the same thing down here for the DES C or the descending table header row and this one's gonna be 2 5 b e ok and then we can just target both of these selectors so we can just say des C here and for both of these we're just going to say margin and - left at 5 pixels to add some space between the actual little icons and the table header text itself okay and then finally we're gonna be targeting our table - sortable and then th sought ASC but this time the actual table header elements themselves and for this we're gonna say des c and then we're going to say background I'm gonna say rgba 0 0 0 and then 0.1 so of course this time round we are going to be selecting or creating a CSS pseudo element for each one of these table header columns that are sorted ascending these ones here are going to be selecting the actual table header elements themselves instead of the pseudo element the actual icon itself okay and this background right here of course adds a darker shade to the background which hopefully should make it look something like this ok so let's just click on this now and as we can see it appears through working perfectly fine now this this shading of the background here is only gonna work if your table table row element has a background color if you are applying your background colors to the table headers themselves then unfortunately this technique right here is not going to work you may want to instead bold your text or do something else to indicate that that is the current column that is being sorted as we can see of course the actual icons themselves for the sorting order is also working perfectly fine so that is how to sort your HTML tables using javascript thanks for watching guys and I'll see you later
Info
Channel: dcode
Views: 53,885
Rating: undefined out of 5
Keywords: code, coding, programming, tutorial, introduction, beginner, walkthrough, guide, software, development, simple, easy, english, with, example, examples, developer, lecture, recording, how, to, web, website, app, application, html, html5, css, css3, js, javascript, es6, ecmascript2015, thead, tbody, tr, td, cell, tables, sort, sorting, algorithm, display, order, ordering, numeric, string, text, data
Id: 8SL_hM1a0yo
Channel Id: undefined
Length: 24min 59sec (1499 seconds)
Published: Mon Feb 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.