Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent part of HTML text from being copied when copying adjacent?

I wrote a JavaScript widget which adds line numbers and one thing I cannot figure out is preventing the numbers from being copied when one copies the text. I want people to be able to copy the sequences around the numbers, but not the numbers. Here is an example of the script's results.

Basically:

<span>useful stuff to be copied </span>
<span style="some-mysterious-setting: True;"> gloss to be discarded in selection </span>
<span> useful stuff to be copied</span>

The numbers are implemented as a separate span elements and not as a table or anything that fancy. I tried user-select: none; and its variants in CSS, but that means it does not get highlighted, but it copies nevertheless the numbering.

like image 517
Matteo Ferla Avatar asked Jan 18 '26 03:01

Matteo Ferla


2 Answers

So you don't need Javascript for this.

The solution is to use a pseudo element and not actually put the number in your element.

<span class="line-number" data-line-number="1"></span>

CSS:

.line-number::before {
  content: attr(data-line-number);
}

td:nth-of-type(1) {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
td:nth-of-type(1)::before {
  content: attr(data-line-number);
}
<table>
  <tr>
    <td data-line-number="1"></td>
    <td>Test row</td>
  </tr>
  <tr>
    <td data-line-number="2"></td>
    <td>Test row</td>
  </tr>
  <tr>
    <td data-line-number="3"></td>
    <td>Test row</td>
  </tr>
  <tr>
    <td data-line-number="4"></td>
    <td>Test row</td>
  </tr>
</table>
like image 155
Alejalapeno Avatar answered Jan 19 '26 16:01

Alejalapeno


You can use CSS counter too to get the result you want, if you have a large amount of data you are no longer in need to specify the line number.

CSS

table
{
    counter-reset: line;
    counter-increment: line;
}

td:nth-of-type(1)::before {
  counter-increment: line+10;
  content: counter(line) " ";
}

td:nth-of-type(1)
{
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

HTML

<table>
  <tr>
    <td></td>
    <td>Row 1</td>
  </tr>
  <tr>
    <td></td>
    <td>Row 2</td>
  </tr>
  <tr>
    <td></td>
    <td>Row 3</td>
  </tr>
  <tr>
    <td></td>
    <td>Row 4</td>
  </tr>
</table>
like image 36
Jaay Avatar answered Jan 19 '26 16:01

Jaay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!