Search code examples
javascripthtmlcss

Unselectable and uncopyable text HTML


This is my attempt below,

/* css */
.unhighlightable-text {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* html */
<div> first </div>
<div class='unhighlightable-text'> second </div> 
<div> third </div>

This works as intended VISUALLY: JSfiddle However if you actually go and copy paste all three divs, 'second' always gets copied.

I looked at Making line numbers uncopyable. But it requires using CSS generated counter to resolve the issue. In my case, the uncopyable portion is generated using JS.

Is there a way to create unselectable and uncopyable text in html without using javascript or restructuring the dom?

Edit

As to why I'm doing this, here is my use case: I have dynamically generated rows of content that I render incrementally. Each row has 2 inline-block divs, the first div contains meta-information, the second div contains useful content. If the user only wants to copy the useful content (which is a frequent usecase), then they will end up copying the first div as well. Since these rows are dynamically rendered (I'm using EmberJS and ember-collection), I can't use a table view and am forced have each row be self-contained.


Solution

  • ::before content will be both unselectable and uncopyable.

    [data-content]::before {
      content: attr(data-content); 
    }
    <div> first </div>
    <div data-content='second'></div>
    <div> third </div>