I'm currently trying to figure out a way to sort a HTML table's column when you click on the relevant header. What's making it challenging is that the table I've made is generated with pure JS, and the only way I've managed to "sort of" capture click events is during the loop when I generate the table headers using onclick
.
Here is the code:
headerArray.forEach(function(heading) {
let el = document.createElement('th');
el.onclick = function(e) {
console.log(e.target);
};
el.appendChild(document.createTextNode(heading));
header.appendChild(el);
});
As you can see, all I'm doing at the moment is outputting to the console. I've tried adding event listeners and the clicks weren't registering. I'm trying to do this in pure JS. Is there an effective way to achieve this even when creating the table dynamically?
My complete function for creating the table is as follows (just for reference the data is loaded in from a JSON object):
function makeTable(data) {
let table = document.createElement('table');
table.id = 'dataTable';
let thead = document.createElement('thead');
table.appendChild(thead);
let tbody = document.createElement('tbody');
table.appendChild(tbody);
let header = document.createElement('tr');
let headerArray = ['Date', 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7'];
let jsonKeys = ['date', 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'];
headerArray.forEach(function(heading) {
let el = document.createElement('th');
el.onclick = function(e) {
console.log(e.target);
};
el.appendChild(document.createTextNode(heading));
header.appendChild(el);
});
thead.appendChild(header);
for (let i = 0; i < Object.keys(data).length; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < jsonKeys.length; j++) {
let el = document.createElement('td');
el.appendChild(document.createTextNode((j == 0) ? formatDate(Object.keys(data)[i].split('-')) : data[Object.keys(data)[i]][jsonKeys[j]]));
tr.appendChild(el);
}
tbody.appendChild(tr);
}
document.body.appendChild(table);
}
What would be the best way for me to accomplish this?