Html – div contentEditable but Readonly

contenteditablehtmlreadonly

I have a div with some text and I want when the cursor is hover this div to select the text. If I let this div as it is, when trying to select all (CTRL+A) then I select all page content, meaning all body text.

To get rid of this, I need to use contenteditable attribute for this div.

But I don't want to let people to change the text / copy / cut and so on

I try to use readonly for this div, but doesn't working.

Any advice please ?

PS1: This div has also other tags inside (html content), but I don't think that this is a problem.

PS2: An example is here: jsfiddle.net/msakamoto_sf/wfae8hzv/ – but with a problem. You can cut the text 🙁

Best Solution

Use event.metaKey in the keydown event to check if ctrl (or cmd on mac) keys are being pressed. You also have to disable the cut and paste events.

<div
  contenteditable="true"
  oncut="return false"
  onpaste="return false"
  onkeydown="if(event.metaKey) return true; return false;">
    content goes here
</div>