Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show blinking text cursor/caret in a read-only div

How can I show a blinking cursor (allowing for text selection via keyboard) in a div but keep it read-only (disallowing text input)?

I know I can set contentEditable to enable the cursor on a div but then users can edit the contents. I've tried adding both contentEditable and readonly to the div but it seems readonly is only effective on input elements, like textarea or input.

I also have tried using a textarea and setting it to readonly so it shows the cursor but doesn't allow text input, like this:

<textarea readonly>Go ahead and move the cursor here but don't try to add text</textarea>

This is the functionality I'm looking for but I want to do this with a div or some other non-input element. I'm open to using 3rd party libraries.


Note: "Cursor" or "caret" here is referring to the blinking lines that indicates where text selection starts/ends.

like image 924
Brady Dowling Avatar asked Feb 15 '19 12:02

Brady Dowling


Video Answer


1 Answers

Here you go :) . All you need to do is disable cut/copy/paste and key press events.

<div
  contenteditable="true"
  oncut="return false"
  onpaste="return false"
  onkeydown="return false;"
  style="user-drag: none;"
  ondragenter="return false;" 
  ondragleave="return false;" 
  ondragover="return false;" 
  ondrop="return false;">
  Inner content
</div>
like image 135
Gaurav Saraswat Avatar answered Sep 22 '22 15:09

Gaurav Saraswat