HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<h1>sotable</h1>
<p>Accessible, sortable HTML table</p>
<table>
<caption>The table is taken from <a href="https://ulf.codes/2012-07-10-five-dysfunctions/">
<em>Five dysfunctions of a team</em>
</a>.</caption>
<thead>
<tr>
<th>Layer</th>
<th>Dysfunction</th>
<th>Behavioral pattern</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Absence of trust</td>
<td>Unwilling to be vulnerable within the group</td>
</tr>
<tr>
<td>2</td>
<td>Fear of conflict</td>
<td>Seeking artificial harmony over a constructive passionate debate</td>
</tr>
<tr>
<td>3</td>
<td>Lack of commitment</td>
<td>Feigning buy-in for group decisions creates ambiguity throughout the organization</td>
</tr>
<tr>
<td>4</td>
<td>Avoidance of accountability</td>
<td>Ducking the responsibility to call peers on counterproductive behavior which sets low standards</td>
</tr>
<tr>
<td>5</td>
<td>Inattention to results</td>
<td>Focusing on personal success, status, and ego before team success</td>
</tr>
</tbody>
</table>
body {
padding: 1rem;
}
table * {
text-align: left;
}
table th, table td {
padding: .5em;
}
th.sotable-column>button,
table.sotable button.restore-order {
all: unset;
/*remove all button styling*/
cursor: pointer;
}
table.sotable button.restore-order {
font-weight: bold;
}
th.sotable-column .indicator {
font-size: smaller;
margin-left: .5em;
}
@media print {
table.sotable caption p.indicator {
display: none;
}
}
//authored by Ulf Schneider
//initial idea from https://www.delftstack.com/howto/javascript/javascript-sort-html-table/
//and incorporated ideas from https://adrianroselli.com/2021/04/sotable-columns.html
//plus my own
const ROW_SELECTOR = 'tr:not(table table tr)';
let defaults = {
indicatorAsc: 'ᐃ',
indicatorDsc: 'ᐁ',
sortHint: 'Sort the table by clicking on a column heading.',
restoreHint: 'Restore the original order by clicking <button>Restore Order</button>.',
whiteList: '',
blackList: ''
}
let settings;
let whiteElements;
let blackElements;
function getArray(value) {
if (value && typeof value === 'string' || value instanceof String) {
return value.split(',');
} else if (value) {
//assuming value is an array
return value;
}
return [];
}
function isWhitelisted(table) {
if (whiteElements.size) {
return whiteElements.has(table);
}
return true;
}
function isBlacklisted(table) {
if (table.classList.contains('no-so')) {
return true;
}
return blackElements.has(table);
}
function setConfig(options) {
settings = Object.assign({}, defaults, options);
whiteElements = new Set();
blackElements = new Set();
for (let white of getArray(settings.whiteList)) {
for (let element of document.querySelectorAll(white)) {
whiteElements.add(element);
}
}
for (let black of getArray(settings.blackList)) {
for (let element of document.querySelectorAll(black)) {
blackElements.add(element);
}
}
}
function getIndexedRowValue(row, columnIndex) {
return row.children[columnIndex].innerText || row.children[columnIndex].textContent;
}
function getColumnIndex(th) {
return Array.from(th.parentNode.children).indexOf(th);
}
function getColumn(table, columnIndex) {
let rows = Array.from(table.querySelectorAll('tr'));
return rows.map(row => row.children[columnIndex]);
}
function canColumnSort(column) {
if (column.length && column[0].tagName != 'TH') {
//first element is not a th
return false;
}
return true;
}
function getBodyRowsContainer(table) {
let tbody = table.querySelector('tbody');
return tbody ? tbody : table;
}
function getBodyRows(table) {
let container = getBodyRowsContainer(table);
return Array.from(container.querySelectorAll(ROW_SELECTOR))
.filter(tr => !tr.querySelector('th:not(table table th)'));
}
function getCellValue(cell) {
return cell.innerText || cell.textContent;
}
function compareValues(value1, value2) {
if (!isNaN(value1) && !isNaN(value2)) {
return value1 - value2;
} else {
return String(value1).localeCompare(String(value2));
}
}
function isColumnAsc(column) {
//is the column sorted ascending?
let values = column.filter(cell => cell.tagName != 'TH').map(cell => getCellValue(cell));
let sortedValues = [...values].sort(compareValues);
return String(values) == String(sortedValues);
}
function comparer(columnIndex, asc) {
//compare table cell values of two rows for the given column index
return function(row1, row2) {
return compareValues(getIndexedRowValue(asc ? row1 : row2, columnIndex), getIndexedRowValue(asc ? row2 : row1, columnIndex));
}
}
function clearTableSortIndication(table) {
//remove all sort indicators
table.querySelectorAll('th.sotable-column:not(table table th)').forEach(th => {
th.classList.remove('asc');
th.classList.remove('dsc');
th.ariaSort = null;
th.querySelectorAll('.indicator').forEach(indicator => indicator.remove());
});
}
function indicateColumnSortDirection(table, th, asc) {
//if the table has been sorted
//provide the indication in the
//column headings
clearTableSortIndication(table);
let indicator = document.createElement('span');
th.firstChild.appendChild(indicator);
indicator.classList.add('indicator');
indicator.ariaHidden = true;
if (asc) {
th.classList.add('asc');
th.ariaSort = 'ascending';
indicator.innerHTML = settings.indicatorAsc;
} else {
th.classList.add('dsc');
th.ariaSort = 'descending';
indicator.innerHTML = settings.indicatorDsc;
}
indicateRestoreTableOrder(table);
}
function storeOrigTableOrder(table) {
//store the original order of the table
//for later re-use
let order = 1;
let bodyRows = getBodyRows(table);
bodyRows.forEach(tr => {
if (!tr.querySelector(`[orig-order]:not(table table [orig-order])`)) {
tr.setAttribute('orig-order', order);
order++;
}
});
}
function restoreOrigTableOrder(table) {
//restore the original order of the table
clearTableSortIndication(table);
let bodyRowsContainer = getBodyRowsContainer(table);
Array.from(bodyRowsContainer.querySelectorAll(`[orig-order]:not(table table [orig-order])`))
.sort((row1, row2) => {
return parseInt(row1.getAttribute('orig-order')) - parseInt(row2.getAttribute('orig-order'));
})
.forEach(tr => bodyRowsContainer.appendChild(tr));
}
function indicateRestoreTableOrder(table) {
//show a hint how to restore the original order
table.querySelectorAll('caption p.indicator:not(table table caption p.indicator)').forEach(indicator => {
if (!indicator.querySelector('.restore-hint') && settings.restoreHint) {
indicator.innerHTML += ` <span class="restore-hint">${settings.restoreHint}</span>`;
//in case the hint contained a button,
//assign a css class and a restore order action to that button
indicator.querySelectorAll('.restore-hint button').forEach(button => {
button.classList.add('restore-order');
button.addEventListener('click', () => {
restoreOrigTableOrder(table);
});
})
}
});
}
function indicateSortableTable(table) {
//prepare a table caption element
//to contain a hint that the table
//can be sorted
let caption = table.querySelector('caption:not(table table caption)');
if (!caption) {
caption = document.createElement('caption');
table.prepend(caption);
}
let indicator = table.querySelector('p.indicator:not(table table p.indicator)');
if (!indicator) {
indicator = document.createElement('p');
indicator.classList.add('indicator');
indicator.innerHTML = settings.sortHint;
caption.appendChild(indicator);
}
indicateRestoreTableOrder(table);
}
function insertColumnSortToggle(th) {
//convert the table th´s so that their previous content
//is wrapped inside of a button element
//that button will toggle the sorting of the column
if (th.querySelectorAll(':not(abbr):not(b):not(br):not(cite):not(code):not(em):not(i):not(img):not(kbd):not(label):not(mark):not(small):not(span):not(strong):not(sub):not(sup):not(svg):not(time)').length) {
//in this case
//we cannot replace the th content with a button
//because buttons are allowed to only contain phrasing content
//https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element
return null;
} else {
//use a button toggle for accessibility
th.innerHTML = `<button>${th.innerHTML}</button>`;
//watch out for the css
//th.sotable-column>button is referring to
//this element
return th.firstChild;
}
}
function sotable(options) {
setConfig(options);
document.querySelectorAll('tr:first-child>th:not(.no-so)').forEach(th => {
let table = th.closest('table');
if (!isBlacklisted(table) && isWhitelisted(table)) {
let columnIndex = getColumnIndex(th);
let column = getColumn(table, columnIndex);
if (canColumnSort(column)) {
storeOrigTableOrder(table);
let toggle = insertColumnSortToggle(th);
if (toggle) {
th.classList.add('sotable-column');
table.classList.add('sotable');
indicateSortableTable(table);
toggle.addEventListener('click', () => {
let asc = !isColumnAsc(getColumn(table, columnIndex));
let bodyRowsContainer = getBodyRowsContainer(table);
let bodyRows = getBodyRows(table);
bodyRows
.sort(comparer(getColumnIndex(th), asc))
.forEach(tr => bodyRowsContainer.appendChild(tr));
indicateColumnSortDirection(table, th, asc);
})
}
}
}
});
}
sotable();
Also see: Tab Triggers