1

I have a sortable table, and I'm adding a way to show you've sorted a column.

The implementation is pretty basic; if you click a unsorted column's header, it appends a ▲ (\u25b2) to the header name. If it's already sorted, it replaces the ▲ with ▼ (\u25bc), or vice versa. This is all done in JavaScript.

Here is my code accomplishing this:

var headerContents = header.innerHTML;

if(headerContents.indexOf('\u25b2') != -1)
    headerContents = headerContents.substring(0, headerContents.length - 1) + '\u25bc';
else if(headerContents.indexOf('\u25bc') != -1)
    headerContents = headerContents.substring(0, headerContents.length - 1) + '\u25b2';
else
    headerContents = headerContents + '\u25b2';

header.innerHTML = headerContents;

My issue is that the arrow is being counted as a separate word (or at least a place where the word can break), so in narrow columns the arrow gets its own line beneath the header name. That looks pretty bad.

Is there a way I can force the arrow to stay on the same line as the header's name? I'd love to keep it in pure JavaScript if possible, as I have many projects with the same JS script I'd like to add this to. If this isn't possible in JavaScript alone, though, I'm open to other solutions.

I've tried adding a non-breaking space (\xa0) between the header and the arrow and I've tried editing the word-break attribute of the header, but neither changed this behavior.

  • Found the dupetarget and deleted my answer. But just double-checking: Are you happy with a CSS solution, or do you actively *want* a JavaScript solution? It would likely be quite complicated... (Unless by a "JavaScript solution" you mean `headerElement.style.whiteSpace = "nowrap";` :-) ) – T.J. Crowder Jan 05 '18 at 15:16
  • 1
    @T.J. Crowder I'm certainly interested in a pure JS approach. I've got quite a few similar pages all using the same .js script, and I'm looking to add this feature to all of them. I'd probably rather write something complicated once than go add `nowrap` to each header on each page. But slapping that line into my JS script is perfectly fine with me, thanks! – user9178110 Jan 05 '18 at 15:18
  • :-) Good enough then. But note that you'd just need to add this in a CSS rule once, and then (say) add a class to the table (assuming it doesn't already have a unique class you could use). E.g., `.the-table-class th { white-space: nowrap; }`. – T.J. Crowder Jan 05 '18 at 15:19

0 Answers0