2

I'm trying to display a div with some example code for users. I want them to be able to select inside the div and use Ctrl + A to select all of the example code, but I don't want them to be able to edit the actual text (lest the remove a bit on accident and then it won't work).

I'm achieving this right now through contenteditable set on the div, but how do I get the same functionality of this attribute sans the actual text editing?

EDIT: Looking at the solution linked in @Mr. Llama's comment, I can use this method to achieve the primary functionality I'm looking for. However, if possible I would like to simply allow for the Ctrl + A command my users are familiar with, and still allow for the manual highlighting of snippets of the div's text. Again, all while disallowing the addition or removal of any text.

Community
  • 1
  • 1
Robert H
  • 67
  • 1
  • 8
  • 1
    Instead of requiring the user to Ctrl + A, you could use a solution like this one: http://stackoverflow.com/q/1173194/477563 – Mr. Llama Sep 21 '15 at 21:19
  • Hm, yes I can use this! However, it would be better for my overall intended functionality if the user could still manually highlight a snippet that they need, but then have the ctrl + A functionality they'd expect. I know I could use an external button to say 'Copy all code' or something but for me that's secondary. When I want to select the entire contents of something I immediately go to Ctrl + A and not a "Copy All" button – Robert H Sep 21 '15 at 21:25

1 Answers1

1

Seems to work for me when I prevent the onkeydown, oncut and onpaste events.

for (const elm of document.getElementsByClassName('editable-not-editable')) {
  elm.setAttribute('contenteditable', true);
  elm.spellcheck = false;
  elm.oncut = () => false;
  elm.onpaste = () => false;
  elm.onkeydown = (event) => {
    if (event.metaKey || event.ctrlKey) {
      return;
    }
    event.preventDefault();
  }
}
<div class="editable-not-editable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
  incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
  exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
  irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
  pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia 
  deserunt mollit anim id est laborum.
</div>
Jan
  • 8,011
  • 3
  • 38
  • 60