responsive-table-fluxbox/js/index3.js

104 lines
2.7 KiB
JavaScript

/*
* Limites de basculements
*/
const minLG = window.matchMedia("(min-width: 801px)");
const maxMD = window.matchMedia("(max-width: 800px)");
const maxSM = window.matchMedia("(max-width: 450px)");
tables.forEach(t => {
const table = document.querySelector(t.id);
/*
* Récupère le texte des entêtes de colonnes
*/
const theadContent = i => {
const thead = table.querySelectorAll(".thead .td");
let content;
thead.forEach((item, j) => {
if (i === j) {
content = item.textContent;
}
}, i);
return content;
};
/*
* Ajoute un nouvel élément thead dans une cellule
*/
const createHeadInto = (cell, i) => {
const elem = document.createElement("div");
elem.classList.add("head");
elem.innerHTML = theadContent(i);
cell.appendChild(elem);
}
/*
* Remove heads from element
*/
const removeHeadsFrom = (element) => {
const heads = element.querySelectorAll(".head");
heads.forEach(head => {
head.parentNode.removeChild(head);
});
};
/*
* Règle pour les écrans moyens
*/
const mediumScreen = rule => {
if (rule.matches) {
console.log('medium');
const rows = [...table.querySelectorAll(".tr")];
rows.shift(); // vire le premier rang
rows.forEach(row => {;
const cells = row.querySelectorAll(".td");
cells.forEach((cell, i) => {
createHeadInto(cell, i);
});
});
} else {
console.log('not medium');
removeHeadsFrom(table);
}
};
/*
* Règle pour les petits écrans
*/
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, i) => {
let head = cell.querySelector('.head');
head.classList.add("td");
row.insertBefore(head, cell);
});
});
} else {
console.log('not small');
const rows = [...table.querySelectorAll(".tr")];
rows.shift();
rows.forEach(row => {;
removeHeadsFrom(row);
if (!minLG.matches) {
const cells = row.querySelectorAll(".td");
cells.forEach((cell, i) => {
createHeadInto(cell, i);
});
}
});
}
};
mediumScreen(maxMD);
maxMD.addListener(mediumScreen);
smallScreen(maxSM);
maxSM.addListener(smallScreen);
});