Skip to content

Commit

Permalink
Better approach for labels using pseudo elements, fix bug with multip…
Browse files Browse the repository at this point in the history
…le child elements in a cell
  • Loading branch information
zachleat committed Oct 4, 2023
1 parent 7c0d9fa commit 1d6fed9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 23 deletions.
2 changes: 1 addition & 1 deletion demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ <h2>Using container queries</h2>
<td>2</td>
<td>1997</td>
<td>88%</td>
<td>$2.1B</td>
<td>$2.1B <a href="">Link</a> test</td>
</tr>
<tr>
<td class="title"><a href="http://en.wikipedia.org/wiki/The_Avengers_(2012_film)">The Avengers</a></td>
Expand Down
42 changes: 20 additions & 22 deletions table-saw.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Tablesaw extends HTMLElement {
breakpointBackwardsCompat: "media",
type: "type",
ratio: "ratio",
label: "data-tablesaw-label",
zeropad: "zero-padding"
};

this.defaults = {
Expand All @@ -20,8 +22,8 @@ class Tablesaw extends HTMLElement {
};

this.classes = {
active: "active",
};
wrap: "tablesaw-wrap"
}

this.props = {
ratio: "--table-saw-ratio",
Expand All @@ -47,22 +49,19 @@ table-saw.${this._identifier} {
display: block;
margin-bottom: 1em;
}
table-saw.${this._identifier} :is(tbody, tfoot) :is(th, td):before {
font-weight: bold;
content: attr(${this.attrs.label});
}
table-saw.${this._identifier} :is(tbody, tfoot) :is(th, td) {
display: grid;
gap: 0 1em;
grid-template-columns: var(--table-saw-ratio, ${this.defaults.ratio});
}
table-saw.${this._identifier}[zero-padding] :is(tbody, tfoot) :is(th, td) {
table-saw.${this._identifier}[${this.attrs.zeropad}] :is(tbody, tfoot) :is(th, td) {
padding-left: 0;
padding-right: 0;
}
table-saw.${this._identifier} .table-saw-label {
display: none;
}
table-saw.${this._identifier} .table-saw-label {
display: revert !important;
}
}`;
}

Expand Down Expand Up @@ -105,20 +104,19 @@ table-saw.${this._identifier} {
return;
}

let nodes = [];
for(let label of labels) {
let l = document.createElement("b");
l.classList.add("table-saw-label");
l.setAttribute("aria-hidden", true);
l.style.display = "none"; // defensive in case the stylesheet insertion fails
l.innerText = label;

nodes.push(l);
}

let cells = this.querySelectorAll("tbody td");
for(let cell of cells) {
cell.prepend(nodes[cell.cellIndex].cloneNode(true));
cell.setAttribute(this.attrs.label, labels[cell.cellIndex]);

// wrap if this cell has child nodes for correct grid alignment
if(cell.firstElementChild) {
let wrapper = document.createElement("div");
wrapper.classList.add(this.classes.wrap);
while(cell.firstChild) {
wrapper.appendChild(cell.firstChild);
}
cell.appendChild(wrapper);
}
}
}

Expand Down

0 comments on commit 1d6fed9

Please sign in to comment.