-
-
Save franklinbaldo/c682d8aa5bb21738bab39ba3c07c4ed8 to your computer and use it in GitHub Desktop.
D3.js Sortable & Responsive Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
First Name | Last Name | Job Title | Favorite Color | Wars or Trek? | Porn Name | Date of Birth | Dream Vacation City | GPA | Arbitrary Data | |
---|---|---|---|---|---|---|---|---|---|---|
James | Matman | Chief Sandwich Eater | Lettuce Green | Trek | Digby Green | January 13, 1979 | Gotham City | 3.1 | RBX-12 | |
The | Tick | Crimefighter Sorta | Blue | Wars | John Smith | July 19, 1968 | Athens | N/A | Edlund, Ben (July 1996). | |
Jokey | Smurf | Giving Exploding Presents | Smurflow | Smurf | Smurflane Smurfmutt | Smurfuary Smurfteenth, 1945 | New Smurf City | 4.Smurf | One | |
Cindy | Beyler | Sales Representative | Red | Wars | Lori Quivey | July 5, 1956 | Paris | 3.4 | 3451 | |
Captain | Cool | Tree Crusher | Blue | Wars | Steve 42nd | December 13, 1982 | Las Vegas | 1.9 | Under the couch |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="javascript" src="http://d3js.org/d3.v3.min.js"></script> | |
<div id="tables></div> | |
<script type="javascript"> | |
csvs = ["data.csv"]; | |
function tabulate(csv) { | |
d3.csv(csv, function(error, data) { | |
if (error) throw error; | |
var sortAscending = true; | |
var table = d3.select('#tables').append('table'); | |
var titles = d3.keys(data[0]); | |
var headers = table.append('thead').append('tr') | |
.selectAll('th') | |
.data(titles).enter() | |
.append('th') | |
.text(function(d) { | |
return d; | |
}) | |
.on('click', function(d) { | |
headers.attr('class', 'header'); | |
if (sortAscending) { | |
rows.sort(function(a, b) { | |
return b[d] < a[d]; | |
}); | |
sortAscending = false; | |
this.className = 'aes'; | |
} else { | |
rows.sort(function(a, b) { | |
return b[d] > a[d]; | |
}); | |
sortAscending = true; | |
this.className = 'des'; | |
} | |
}); | |
var rows = table.append('tbody').selectAll('tr') | |
.data(data).enter() | |
.append('tr'); | |
rows.selectAll('td') | |
.data(function(d) { | |
return titles.map(function(k) { | |
return { | |
'value': d[k], | |
'name': k | |
}; | |
}); | |
}).enter() | |
.append('td') | |
.attr('data-th', function(d) { | |
return d.name; | |
}) | |
.text(function(d) { | |
return d.value; | |
}); | |
}); | |
} | |
csvs.forEach(tabulate); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment