Skip to content

Instantly share code, notes, and snippets.

@dgrammatiko
Created March 29, 2021 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgrammatiko/4d8121c2cda4096224d4de283a1a433a to your computer and use it in GitHub Desktop.
Save dgrammatiko/4d8121c2cda4096224d4de283a1a433a to your computer and use it in GitHub Desktop.
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