Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an invisible character in HTML, that still get's picked up on text selection?

Backstory

So I am doing a webchat as a side-project, and one of the issues I am encountering is making the UX of copying and pasting messages friendly.

Right now all of the elements are organized within their own tags, spaced out and separated with CSS rules, in a way that if you try copying a part of the chat log, it comes out as 23:49userHello World.

The solution I have thought of is to have a zero-width tab character separating them, that still gets picked up by text selection, and when pasted as raw text is just a normal tab. This would not only separate it in copy paste actions, but it would make it super easy to parse using awk.

TL;DR

How would I modify a printable tab character (	) with CSS, or any character by that matter, in a way that it's invisible to the layout, but still gets picked up in text selections?

like image 556
Luiz Berti Avatar asked Oct 20 '22 17:10

Luiz Berti


1 Answers

As all of the elements are organized within their own tags, you could use :after with the character that you want as separator in the content (with font-size:0). As far as I know, this solution will only work on IE, as the other browsers don't select the pseudo-elements):

span:after {
    content: " ";
    font-size:0;
}

You can see it on this jsfiddle: http://jsfiddle.net/bc7jrdff/1/ (Remember only on IE!)

Another CSS possibility would be to add the special character directly when you generate the page, and apply the ::first-letter pseudo-element. The problem of this solution is that not all characters will count as a first letter (blank space doesn't)

Using JavaScript, you could come up with a solution that works in all the browsers: append your character to the elements (again with font-size:0):

// CSS
span.hiddenChar {
    font-size:0;
}

// JS
$(document).ready(function() {
    $("span").prepend("<span class='hiddenChar'> </span>");
});

You can see it working here: http://jsfiddle.net/bc7jrdff/2/

Or if you prefer JavaScript without jQuery:

// HTML
<span class="data">23:49</span><span class="data">user</span><span class="data">Hello World!</span>

// JS
var aux = document.querySelectorAll(".data");
for (x = 0; x < aux.length; x++) {
    aux[x].innerHTML = "<span class='hiddenChar'> </span>" + aux[x].innerHTML;
};

You can see that on this jsFiddle: http://jsfiddle.net/bc7jrdff/4/

like image 71
Alvaro Montoro Avatar answered Nov 01 '22 13:11

Alvaro Montoro