Brady Dowling
Brady Dowling

Reputation: 5532

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.

Upvotes: 5

Views: 3130

Answers (2)

Gaurav Saraswat
Gaurav Saraswat

Reputation: 1383

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>

Upvotes: 7

Abderrahmane TAHRI JOUTI
Abderrahmane TAHRI JOUTI

Reputation: 4283

In Vanilla JavaScript, This is the simplest example of how you can go about doing it. I am using a class here, but as other answers showed, you could change it to an actual attribute or whatever suits your linking.

  const uneditables = Array.from(
        document.querySelectorAll(".editable-but-not-really")
  );

  const doNothing = e => e.preventDefault();

  uneditables.forEach(element => {
    element.setAttribute("contentEditable", true);
    element.addEventListener("oncut", doNothing, false);
    element.addEventListener("onpaste", doNothing, false);
    element.addEventListener("keydown", doNothing, false);
  });
<div class="editable-but-not-really">I am here to stay</div>
<div class="editable-but-not-really">You cannot edit me</div>
<div class="editable-but-not-really">I was born to stay</div>
<div class="editable-but-not-really">As I am, and I don't</div>
<div class="editable-but-not-really">want anything to do with</div>
<div class="editable-but-not-really">your stinky pointer</div>

Upvotes: 1

Related Questions