/    Sign up×
Community /Pin to ProfileBookmark

I want to add an up/down arrowhead to indicate column sort order

I have two examples of Javascript that sorts a column of a table, one is very concise but doesn’t show the sort order, the other is very long but does show the sort order. I thought it would be simple to lift the arrowhead code and put it into the nice concise bit of code but it defeats me, maybe someone can point me in the right direction – no pun intended! And I’ve no idea why the following is bold – this is weird!!!
(Note: I pasted the code using the insert code option but it didn’t exactly work so I abandoned that and just pasted the code as is.)


=============================================

With Arrowheads – using ascii codes 25b2 and 25bc


=============================================
[code]<html>
<head>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width”>
<title>TestSortArrows – html</title>

<script>
function sortTable(Table, col, dir) {
var sortClass, i;

sortTable.sortCol = -1;
sortClass = Table.className.match(/js-sort-d+/);
if (null != sortClass) {
sortTable.sortCol = sortClass[0].replace(/js-sort-/, ”);
Table.className = Table.className.replace(new RegExp(‘ ?’ + sortClass[0] + ‘\b’), ”);
}
if (‘undefined’ === typeof col) {
col = sortTable.sortCol;
}

if (‘undefined’ !== typeof dir) {
sortTable.sortDir = dir == -1 || dir == ‘desc’ ? -1 : 1;
} else {
sortClass = Table.className.match(/js-sort-(a|de)sc/);
if (null != sortClass && sortTable.sortCol == col) {
sortTable.sortDir = ‘js-sort-asc’ == sortClass[0] ? -1 : 1;
} else {
sortTable.sortDir = 1;
}
}
Table.className = Table.className.replace(/ ?js-sort-(a|de)sc/g, ”);

Table.className += ‘ js-sort-‘ + col;
sortTable.sortCol = col;

Table.className += ‘ js-sort-‘ + (sortTable.sortDir == -1 ? ‘desc’ : ‘asc’);

if (col < Table.tHead.rows[Table.tHead.rows.length – 1].cells.length) {
sortClass = Table.tHead.rows[Table.tHead.rows.length – 1].cells[col].className.match(/js-sort-[-w]+/);
}
for (i = 0; i < Table.tHead.rows[Table.tHead.rows.length – 1].cells.length; i++) {
if (col == Table.tHead.rows[Table.tHead.rows.length – 1].cells[i].getAttribute(‘data-js-sort-colNum’)) {
sortClass = Table.tHead.rows[Table.tHead.rows.length – 1].cells[i].className.match(/js-sort-[-w]+/);
}
}
if (null != sortClass) {
sortTable.sortFunc = sortClass[0].replace(/js-sort-/, ”);
} else {
sortTable.sortFunc = ‘string’;
}
Table.querySelectorAll(‘.js-sort-active’).forEach(function(Node) {
Node.className = Node.className.replace(/ ?js-sort-activeb/, ”);
});
Table.querySelectorAll(‘[data-js-sort-colNum=”‘ + col + ‘”]:not(:empty)’).forEach(function(Node) {
Node.className += ‘ js-sort-active’;
});

var rows = [],
TBody = Table.tBodies[0];

for (i = 0; i < TBody.rows.length; i++) {
rows[i] = TBody.rows[i];
}
if (‘none’ != sortTable.sortFunc) {
rows.sort(sortTable.compareRow);
}

while (TBody.firstChild) {
TBody.removeChild(TBody.firstChild);
}
for (i = 0; i < rows.length; i++) {
TBody.appendChild(rows[i]);
}
}

sortTable.compareRow = function(RowA, RowB) {
var valA, valB;
if (‘function’ != typeof sortTable[sortTable.sortFunc]) {
sortTable.sortFunc = ‘string’;
}
valA = sortTable[sortTable.sortFunc](RowA.cells[sortTable.sortCol]);
valB = sortTable[sortTable.sortFunc](RowB.cells[sortTable.sortCol]);

return valA == valB ? 0 : sortTable.sortDir * (valA > valB ? 1 : -1);
};

sortTable.stripTags = function(html) {
return html.replace(/</?[a-z][a-z0-9]*b[^>]*>/gi, ”);
};

sortTable.date = function(Cell) {
// If okDate library is available, Use it for advanced Date processing
if (okDate) {
var Date = okDate(sortTable.stripTags(Cell.innerHTML));
return Date ? Date.getTime() : 0;
} else {
return (new Date(sortTable.stripTags(Cell.innerHTML))).getTime() || 0;
}
};

sortTable.number = function(Cell) {
return Number(sortTable.stripTags(Cell.innerHTML).replace(/[^-d.]/g, ”));
};

sortTable.string = function(Cell) {
return sortTable.stripTags(Cell.innerHTML).toLowerCase();
};

sortTable.raw = function(Cell) {
return Cell.innerHTML;
};

sortTable.last = function(Cell) {
return sortTable.stripTags(Cell.innerHTML).split(‘ ‘).pop().toLowerCase();
};

sortTable.input = function(Cell) {
for (var i = 0; i < Cell.children.length; i++) {
if (‘object’ == typeof Cell.children[i]
&& ‘undefined’ != typeof Cell.children[i].value
) {
return Cell.children[i].value.toLowerCase();
}
}

return sortTable.string(Cell);
};

sortTable.none = function(Cell) {
return null;
};

sortTable.getClickHandler = function(Table, col) {
return function() {
sortTable(Table, col);
};
};

sortTable.init = function() {
var THead, Tables, Handler;
if (document.querySelectorAll) {
Tables = document.querySelectorAll(‘table.js-sort-table’);
} else {
Tables = document.getElementsByTagName(‘table’);
}

for (var i = 0; i < Tables.length; i++) {
if (!document.querySelectorAll && null === Tables[i].className.match(/bjs-sort-tableb/)) {
continue;
}

if (Tables[i].attributes[‘data-js-sort-table’]) {
continue;
}

if (!Tables[i].tHead) {
THead = document.createElement(‘thead’);
THead.appendChild(Tables[i].rows[0]);
Tables[i].insertBefore(THead, Tables[i].children[0]);
} else {
THead = Tables[i].tHead;
}

for (var rowNum = 0; rowNum < THead.rows.length; rowNum++) {
for (var cellNum = 0, colNum = 0; cellNum < THead.rows[rowNum].cells.length; cellNum++) {
THead.rows[rowNum].cells[cellNum].setAttribute(‘data-js-sort-colNum’, colNum);
Handler = sortTable.getClickHandler(Tables[i], colNum);
window.addEventListener
? THead.rows[rowNum].cells[cellNum].addEventListener(‘click’, Handler)
: window.attachEvent && THead.rows[rowNum].cells[cellNum].attachEvent(‘onclick’, Handler);
colNum += THead.rows[rowNum].cells[cellNum].colSpan;
}
}

Tables[i].setAttribute(‘data-js-sort-table’, ‘true’)
}

var element = document.createElement(‘style’);
document.head.insertBefore(element, document.head.childNodes[0]);
var sheet = element.sheet;
//
// Set up and down arrows using ascii codes 25b2 and 25bc
//
sheet.insertRule(‘table.js-sort-asc thead tr > .js-sort-active:not(.js-sort-none):after {content: “\25b2”;font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}’, 0);
sheet.insertRule(‘table.js-sort-desc thead tr > .js-sort-active:not(.js-sort-none):after {content: “\25bc”;font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}’, 0);
};

// Run sortTable.init() when the page loads
window.addEventListener
? window.addEventListener(‘load’, sortTable.init, false)
: window.attachEvent && window.attachEvent(‘onload’, sortTable.init)
;

if (typeof NodeList.prototype.forEach !== “function”) {
NodeList.prototype.forEach = Array.prototype.forEach;
}
</script>

</head>
<body>

<H3>Test Sorting table – TestSortArrows.html</h3>
<!— <table border=1 cellspacing=0> —>
<table class=”js-sort-table” border=1 cellspacing=0> <!— id=”demo1″ —>

<thead>
<tr>
<th>Asset No</th>
<th>Description</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>JKEL03001234</td><td>Emergency Light</td><td>Rm 35</td>
</tr>
<tr>
<td>JKEL03001239</td><td>Emergency Light</td><td>Rm 36</td>
</tr>
<tr>
<td>JKEP01001234</td><td>Emergency Power Off</td><td>Rm 37</td>
</tr>
<tr>
<td>JKED03001234</td><td>Emergency Door</td><td>Rm 38</td>
</tr>
</tbody>
</table>
</body>
</html>[/code]

===========================================================================
And the without arrowheads example – I know what to insert – I don’t know where.

==========================================================================
Without Arrowheads – I need to insert these somewhere using ascii codes 25b2 and 25bc


===========================================================================
[code]<!DOCTYPE html>
<!— https://jsbin.com/?html,output —>
<html>
<head>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width”>
<title>TestNoSortArrows</title>

<script>
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (–i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener(‘click’, function () {sortTable(table, i, (dir = 1 – dir))});
}(i));
}

function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName(‘table’), i = t.length;
while (–i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};
</script>

</head>
<body>

<H3>Test Sorting table – TestNoSortArrows.html</h3>
<!— <table border=1 cellspacing=0> —>
<table class=”js-sort-table” id=”demo1″ border=1 cellspacing=0>

<thead>
<tr>
<th>Asset No</th>
<th>Description</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>JKEL03001234</td><td>Emergency Light</td><td>Rm 35</td>
</tr>
<tr>
<td>JKEL03001239</td><td>Emergency Light</td><td>Rm 36</td>
</tr>
<tr>
<td>JKEP01001234</td><td>Emergency Power Off</td><td>Rm 37</td>
</tr>
<tr>
<td>JKED03001234</td><td>Emergency Door</td><td>Rm 38</td>
</tr>
</tbody>
</table>
</body>
</html>[/code]

================================================================

Thanks folks

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — Note: I pasted the code using the insert code option but it didn't exactly work so I abandoned that and just pasted the code as is.[/quote]Use code tags instead: `your code here`

I edited your posting accordingly.
Copy linkTweet thisAlerts:
@CYPRUSBREWauthorJun 14.2020 — @Sempervivum#1619512

Cheers, noted for for my next post - much appreciated, yo could help more, what about the unintentional bold typeface, I used the B option - could I use [bold][/bold]?
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — You can use `[b]bold text[/b]</C> or <C>**bold text**`. The latter is faster to type in. Give it a try.

More bbcode:

https://www.bbcode.org/examples/
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — what about the unintentional bold typeface[/quote]I used the edit function and found out that a line is formatted that strong when it is followed by a `=` in the next line.
Copy linkTweet thisAlerts:
@CYPRUSBREWauthorJun 14.2020 — @Sempervivum#1619515 That may be because I used a load of =signs to separate my examples, and another question, I cannot edit my original post anymore - is that because it has a reply?
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — I'm not sure about that, I suspect the reason is that editing is enabled only after a certain amount of postings. I edited your posting again, the bold formatting disappears when I add a leading blank to the line containing the = characters.
Copy linkTweet thisAlerts:
@CYPRUSBREWauthorJun 14.2020 — @Sempervivum#1619518 I edited it just after I posted it and saw the code tagging hadn't worked as I expected, edit was enabled till you replied - kind of makes sense to lock a post once it's received a reply. Cheers
Copy linkTweet thisAlerts:
@CYPRUSBREWauthorJun 15.2020 — I've added the arrowhead code but it doesn't display hem, where am I going wrong?

I've put comments around the code I've added, but I'm stuck - I think the inserted code isn't referencing the table correctly but not to sure wher
[CODE]
<!DOCTYPE html>
<!--- https://jsbin.com/?html,output --->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>TestNoSortArrows</title>


<script>
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use &lt;tbody&gt; to ignore &lt;thead&gt; and &lt;tfoot&gt; rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // -1 * if want opposite order
* (a.cells[col].textContent.trim() // using .textContent.trim() for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
//
// Inserted from the Arrowhead script
//
var element = document.createElement('style');
document.head.insertBefore(element, document.head.childNodes[0]);
var sheet = element.sheet;
//
// Set up and down arrows using ascii codes 25b2 and 25bc - but it doesn't work
//
sheet.insertRule('table.js-sort-asc thead tr > .js-sort-active:not(.js-sort-none):after {content: "\25b2";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 0);
sheet.insertRule('table.js-sort-desc thead tr > .js-sort-active:not(.js-sort-none):after {content: "\25bc";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 0);

//
// Inserted from the Arrowhead script
//

}

function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no &lt;thead&gt; then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}

function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
</script>

</head>
<body>
<H3>Test Sorting table - TestNoSortArrows.html</h3>
<!--- <table border=1 cellspacing=0> --->
<table class="js-sort-table" border=1 cellspacing=0> <!-- id="demo1" -->

<thead>
<tr>
<th>Asset No</th>
<th>Description</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>JKEL03001234</td><td>Emergency Light</td><td>Rm 35</td>
</tr>
<tr>
<td>JKEL03001239</td><td>Emergency Light</td><td>Rm 36</td>
</tr>
<tr>
<td>JKEP01001234</td><td>Emergency Power Off</td><td>Rm 37</td>
</tr>
<tr>
<td>JKED03001234</td><td>Emergency Door</td><td>Rm 38</td>
</tr>
</tbody>
</table>
</body>

Cheers folks
</html>
[/CODE]
Copy linkTweet thisAlerts:
@SempervivumJun 15.2020 — a) You have to define the styles for the arrowheads in function makeSortable()

b) You have to add the appropriate class in function sortTable()

This works for me (I've simplified the selectors for the arrowheads a bit):
&lt;!DOCTYPE html&gt;
&lt;!--- https://jsbin.com/?html,output ---&gt;
&lt;html&gt;

&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;meta name="viewport" content="width=device-width"&gt;
&lt;title&gt;TestNoSortArrows&lt;/title&gt;


<i> </i>&lt;script&gt;
<i> </i> function sortTable(table, col, reverse) {
<i> </i> var tb = table.tBodies[0], // use <span><code>&amp;lt;tbody&amp;gt;</code></span> to ignore <span><code>&amp;lt;thead&amp;gt;</code></span> and <span><code>&amp;lt;tfoot&amp;gt;</code></span> rows
<i> </i> tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
<i> </i> i;
<i> </i> reverse = -((+reverse) || -1);
<i> </i> var sortingClass = '';

<i> </i> // define class for arrowheads
<i> </i> if (reverse == 1) sortingClass = 'js-sort-desc';
<i> </i> else sortingClass = 'js-sort-asc';
<i> </i> var trHead = table.tHead.rows[0];
<i> </i> // remove all classes for arrowheads
<i> </i> for (i = 0; i &lt; trHead.cells.length; i++) {
<i> </i> trHead.cells[i].classList.remove('js-sort-asc');
<i> </i> trHead.cells[i].classList.remove('js-sort-desc');
<i> </i> }
<i> </i> // set class for current arrowhead
<i> </i> table.tHead.rows[0].cells[col].classList.add(sortingClass);

<i> </i> tr = tr.sort(function (a, b) { // sort rows
<i> </i> return reverse // <span><code>-1 *</code></span> if want opposite order
<i> </i> * (a.cells[col].textContent.trim() // using <span><code>.textContent.trim()</code></span> for test
<i> </i> .localeCompare(b.cells[col].textContent.trim())
<i> </i> );
<i> </i> });
<i> </i> for (i = 0; i &lt; tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
<i> </i> }

<i> </i> function makeSortable(table) {
<i> </i> var th = table.tHead, i;
<i> </i> th &amp;&amp; (th = th.rows[0]) &amp;&amp; (th = th.cells);
<i> </i> if (th) i = th.length;
<i> </i> else return; // if no <span><code>&amp;lt;thead&amp;gt;</code></span> then do nothing
<i> </i> while (--i &gt;= 0) (function (i) {
<i> </i> var dir = 1;
<i> </i> th[i].addEventListener('click', function () { sortTable(table, i, (dir = 1 - dir)) });
<i> </i> }(i));

<i> </i> //
<i> </i> // Inserted from the Arrowhead script
<i> </i> //
<i> </i> var element = document.createElement('style');
<i> </i> document.head.insertBefore(element, document.head.childNodes[0]);
<i> </i> var sheet = element.sheet;
<i> </i> //
<i> </i> // Set up and down arrows using ascii codes 25b2 and 25bc - but it doesn't work
<i> </i> //
<i> </i> // sheet.insertRule('table.js-sort-asc thead tr &gt; .js-sort-active:not(.js-sort-none):after {content: "\25b2";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 0);
<i> </i> // sheet.insertRule('table.js-sort-desc thead tr &gt; .js-sort-active:not(.js-sort-none):after {content: "\25bc";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 1);
<i> </i> sheet.insertRule('table thead tr &gt; th.js-sort-asc:after {content: "\25b2";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 0);
<i> </i> sheet.insertRule('table thead tr &gt; th.js-sort-desc:after {content: "\25bc";font-size: 0.7em;padding-left: 3px;line-height: 0.7em;}', 1);

<i> </i> //
<i> </i> // Inserted from the Arrowhead script
<i> </i> //

<i> </i> }

<i> </i> function makeAllSortable(parent) {
<i> </i> parent = parent || document.body;
<i> </i> var t = parent.getElementsByTagName('table'), i = t.length;
<i> </i> while (--i &gt;= 0) makeSortable(t[i]);
<i> </i> }
<i> </i> window.onload = function () { makeAllSortable(); };
<i> </i>&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;H3&gt;Test Sorting table - TestNoSortArrows.html&lt;/h3&gt;
&lt;!--- &lt;table border=1 cellspacing=0&gt; ---&gt;
&lt;table class="js-sort-table" border=1 cellspacing=0&gt;
&lt;!-- id="demo1" --&gt;

<i> </i> &lt;thead&gt;
<i> </i> &lt;tr&gt;
<i> </i> &lt;th&gt;Asset No&lt;/th&gt;
<i> </i> &lt;th&gt;Description&lt;/th&gt;
<i> </i> &lt;th&gt;Location&lt;/th&gt;
<i> </i> &lt;/tr&gt;
<i> </i> &lt;/thead&gt;
<i> </i> &lt;tbody&gt;
<i> </i> &lt;tr&gt;
<i> </i> &lt;td&gt;JKEL03001234&lt;/td&gt;
<i> </i> &lt;td&gt;Emergency Light&lt;/td&gt;
<i> </i> &lt;td&gt;Rm 35&lt;/td&gt;
<i> </i> &lt;/tr&gt;
<i> </i> &lt;tr&gt;
<i> </i> &lt;td&gt;JKEL03001239&lt;/td&gt;
<i> </i> &lt;td&gt;Emergency Light&lt;/td&gt;
<i> </i> &lt;td&gt;Rm 36&lt;/td&gt;
<i> </i> &lt;/tr&gt;
<i> </i> &lt;tr&gt;
<i> </i> &lt;td&gt;JKEP01001234&lt;/td&gt;
<i> </i> &lt;td&gt;Emergency Power Off&lt;/td&gt;
<i> </i> &lt;td&gt;Rm 37&lt;/td&gt;
<i> </i> &lt;/tr&gt;
<i> </i> &lt;tr&gt;
<i> </i> &lt;td&gt;JKED03001234&lt;/td&gt;
<i> </i> &lt;td&gt;Emergency Door&lt;/td&gt;
<i> </i> &lt;td&gt;Rm 38&lt;/td&gt;
<i> </i> &lt;/tr&gt;
<i> </i> &lt;/tbody&gt;
<i> </i>&lt;/table&gt;
&lt;/body&gt;

Cheers folks

&lt;/html&gt;
Copy linkTweet thisAlerts:
@CYPRUSBREWauthorJun 15.2020 — Brilliant, many thanks I've learnt something today and I'll be adding this to my notes. 😃

Cheers
×

Success!

Help @CYPRUSBREW spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...