/* * Add heads elements into row */ const createHeadsIntoRow = (table, row) => { const cells = row.querySelectorAll(".td"); cells.forEach((cell, i) => { createHeadIntoCell(table, cell, i); }); }; /* * Add head into cell */ const createHeadIntoCell = (table, cell, i) => { const elem = document.createElement("div"); elem.classList.add("head"); elem.innerHTML = theadContent(table, i); cell.appendChild(elem); } /* * Get text in columns thead */ const theadContent = (table, i) => { const thead = table.querySelectorAll(".thead .td"); let content; thead.forEach((item, j) => { if (i === j) { content = item.textContent; } }, i); return content; }; /* * Remove heads from element */ const removeHeadsFrom = (element) => { const heads = element.querySelectorAll(".head"); heads.forEach(head => { head.parentNode.removeChild(head); }); }; /* * Insert head before cell */ const insertHeadBeforeCell = (row, cell) => { let head = cell.querySelector('.head'); head.classList.add("td"); row.insertBefore(head, cell); }; /* * Loop on each table */ tables.forEach(t => { const table = document.querySelector(`#${t.id}`); /* * Responsive rules limits */ const minLG = window.matchMedia(`(min-width: ${t.md_lg + 1}px)`); const maxMD = window.matchMedia(`(max-width: ${t.md_lg}px)`); const maxSM = window.matchMedia(`(max-width: ${t.sm_md}px)`); /* * Medium screens rule */ const mediumScreen = rule => { if (rule.matches) { console.log('medium'); const rows = [...table.querySelectorAll(".tr")]; rows.shift(); // vire le premier rang rows.forEach(row => { createHeadsIntoRow(table, row); }); } else { console.log('not medium'); removeHeadsFrom(table); } }; /* * Small screens rule */ const smallScreen = (rule) => { if (rule.matches) { console.log('small'); const rows = [...table.querySelectorAll(".tr")]; rows.shift(); rows.forEach(row => {; const cells = row.querySelectorAll(".td"); cells.forEach(cell => { insertHeadBeforeCell(row, cell); }); }); } else { console.log('not small'); const rows = [...table.querySelectorAll(".tr")]; rows.shift(); rows.forEach(row => {; removeHeadsFrom(row); // Large screen exception ! if (!minLG.matches) { createHeadsIntoRow(table, row); } }); } }; mediumScreen(maxMD); maxMD.addListener(mediumScreen); smallScreen(maxSM); maxSM.addListener(smallScreen); });