readonly div in CSS or JavaScript

KarSho picture KarSho · Mar 20, 2013 · Viewed 84.7k times · Source

I need to make 'read-only div' using with CSS or JavaScript or Jquery. Not only text-box and all. Full div. That div contain anything(image, ,other div,text-box,...)

That should support by all Browser.

Any idea?

Answer

novalagung picture novalagung · Mar 20, 2013

You could use pointer-events: none; to disable mouse DOM interaction (like click, hover, etc) on certain element. Example:

div {
    pointer-events: none;
}
<div>
    <input type="text" value="value" />
    <br />
    <textarea>value</textarea>
</div>

However, even though pointer-events: none; is there, it's still possible to make the cursor to be focus on the element (or it's children). Meaning if we move the cursor focus on the <input /> tag, then it's possible to edit the value.

Example: try to click the <input /> tag, then press tab in keyboard, the cursor focus will be on input, making it editable.


To make <input /> tag completely un-editable, put readonly attribute on the tag. Below is simple example to do it by using jQuery .prop(). You can also put the attribute directly on the tag, depending on the needs.

$("input, textarea").prop("readonly", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" value="value" />
  <br />
  <textarea>value</textarea>
</div>