Created
March 29, 2021 14:38
-
-
Save dgrammatiko/4d8121c2cda4096224d4de283a1a433a to your computer and use it in GitHub Desktop.
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
if (window.innerWidth > 1024) { | |
const table = document.querySelector('table.itemList'); | |
if (!table) { | |
throw new Error('A table is needed'); | |
} | |
const thead = table.querySelector('thead tr'); | |
if (!thead) { | |
throw new Error('A thead element is needed'); | |
} | |
const headers = [].slice.call(thead.children); | |
const rows = [].slice.call(table.querySelectorAll('tbody tr')); | |
if (!rows.length) { | |
throw new Error('The table needs rows'); | |
} | |
headers.forEach((el) => { | |
el.classList.remove('d-none', 'd-md-table-cell', 'd-lg-table-cell'); | |
}); | |
rows.forEach((col) => { | |
[].slice.call(col.children).forEach((cc) => { | |
cc.classList.remove('d-none', 'd-md-table-cell', 'd-lg-table-cell'); | |
}); | |
}); | |
const toggleHidden = (index) => { | |
headers[index].classList.toggle('d-none'); | |
rows.forEach((col) => { | |
col.children[index].classList.toggle('d-none'); | |
}); | |
}; | |
const detailElement = document.createElement('details'); | |
const summary = document.createElement('summary'); | |
summary.innerText = 'Table options'; | |
detailElement.appendChild(summary); | |
const ul = document.createElement('ul'); | |
headers.forEach((el, index) => { | |
if (index === 0 || index === headers.length - 1) return; | |
const li = document.createElement('li'); | |
const label = document.createElement('label'); | |
const input = document.createElement('input'); | |
input.type = 'checkbox'; | |
input.setAttribute('checked', ''); | |
input.addEventListener('input', () => toggleHidden(index)); | |
label.innerText = el.querySelector('span').innerText || el.innerText; | |
label.insertAdjacentElement('afterbegin', input); | |
li.appendChild(label); | |
ul.appendChild(li); | |
}); | |
detailElement.appendChild(ul); | |
table.insertAdjacentElement('beforebegin', detailElement); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment