Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restrict the range of select all/Ctrl+A?

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/

like image 456
Daniel Trebbien Avatar asked Sep 30 '22 10:09

Daniel Trebbien


1 Answers

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.

like image 131
lokeshpahal Avatar answered Oct 04 '22 21:10

lokeshpahal