Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all text in contenteditable div when it focus/click [duplicate]

I've got contenteditable div as below.

<div style=" border:solid 1px #D31444" contenteditable="true">12 some text...</div> 

What I need is, when I click on the div, all the text will automatically get selected. Can you give me solution please?

like image 216
angry kiwi Avatar asked Sep 27 '10 16:09

angry kiwi


People also ask

How do I select all text in a div?

To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.

How do you focus on Contenteditable?

Changing your tabIndex to >= 0 will let you focus on the elements. If you need to do it dynamically, you can just add a tabindex >= 0 to your element in the event listener.

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.


2 Answers

This will do it. The timer is there for Chrome and Safari because in those browsers, the native browser behaviour that selects the whole element seems to trigger after the focus event, thereby overriding the effect of the selection code unless postponed until after the focus event:

var div = document.getElementById("editable");  div.onfocus = function() {     window.setTimeout(function() {         var sel, range;         if (window.getSelection && document.createRange) {             range = document.createRange();             range.selectNodeContents(div);             sel = window.getSelection();             sel.removeAllRanges();             sel.addRange(range);         } else if (document.body.createTextRange) {             range = document.body.createTextRange();             range.moveToElementText(div);             range.select();         }     }, 1); }; 
like image 71
Tim Down Avatar answered Sep 18 '22 13:09

Tim Down


Try this:

<div style="border:solid 1px #D31444"      contenteditable="true"      onclick="document.execCommand('selectAll',false,null)">12 some text...</div> 

Update: Note that document.execCommand is now deprecated although it still works.

like image 38
Danylo Mysak Avatar answered Sep 21 '22 13:09

Danylo Mysak