5

I am working on a website where I would like to be able to display a box containing syntax-highlighted source code for the user to copy. When I click on the box, giving it focus (Chrome shows its focus outline), and type Ctrl+A, the text of the entire page is selected, whereas I would like only the syntax-highlighted source code within the box to be selected.

Is it possible to restrict the range of select all/Ctrl+A to only the text within the box, preferably without using an <iframe>?

My first thought was to try contenteditable. When I click in the box and the editor caret appears, typing Ctrl+A selects only the text within the box, as desired, but it also allows the user to change the code, and I think that the editor-interface aspect of making the box contenteditable will be confusing to users. If I wrap the source code text within a <div> having contenteditable="false" within the <div> having contenteditable="true", then the source code text is read-only, but typing Ctrl+A selects the text of the entire page again.

Here is a test page: http://jsfiddle.net/5crgL/

Daniel Trebbien
  • 35,770
  • 14
  • 104
  • 182

1 Answers1

4

You can use the document.createRange(); method to select the text from a particular element. and to handle the ctrl+a you can use the jQuery keydown method and can call the JS code to select the DIV text.

var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);

please see jsfiddle here jsfiddle.

lokeshpahal
  • 521
  • 4
  • 11
  • 1
    The only problem with your solution is that no matter where the user is, it only selects the text in the container. There should probably be a mouse listener to get the mouse position and only grab the container text if the mouse is hovering inside/over the container. – RevanProdigalKnight Jul 03 '14 at 12:34
  • for this you can use jQuery `is(':hover')` to detect if mouse hover over DIV. please find update `jsfiddle` http://jsfiddle.net/5crgL/5/ – lokeshpahal Jul 03 '14 at 12:41
  • Also you match against a certain key-combination, but hotkeys can differ. Mac for example uses cmd + a or users could even configure their own hotkeys. – Linus Jul 03 '14 at 12:41
  • Works perfectly on Windows. On Mac, there is an issue where this doesn't work with ⌘A, but I think that that will just require a small tweak. – Daniel Trebbien Jul 03 '14 at 13:14
  • Yes you can adjust the code by identifying the os and browser. – lokeshpahal Jul 03 '14 at 15:47
  • Chrome gives the message: `Selection.addRange() is deprecated and will be removed from Chrome`. A simple solution can be found [here](https://stackoverflow.com/questions/43260617/selection-addrange-is-deprecated-and-will-be-removed-from-chrome). – OfirD Jan 16 '20 at 17:14