How to select all text in contenteditable div?
Great function.
I've adapted it to enable full selection of text across any number of editable divs via a class, whether clicked directly, or tabbed to:
$.fn.selectText = function(){
var doc = document;
var element = this[0];
//console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$(".editable").on("focus", function () {
$(this).selectText();
});
$(".editable").on("click", function () {
$(this).selectText();
});
$('.editable').mouseup(function(e){
e.stopPropagation();
e.preventDefault();
// maximize browser compatability
e.returnValue = false;
e.cancelBubble = true;
return false;
});
HTML:
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">01 text...</div>
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">02 text...</div>
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">03 text...</div>
FIDDLE:
http://jsfiddle.net/tw9jwjbv/
I used some code from this thread to come up with my answer. It's 100% jQuery as you asked for as well. Hope you like it :)
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("button").click(function() {
$("#editable").selectText();
});
jsfiddle link.
For example in next scenario if user set focus into editable div (with mouse, keyboard or by clicking a button) then content of editable div is selected.
<div id="editable" style=" border:solid 1px #D31444" contenteditable="true"
onfocus="document.execCommand('selectAll', false, null);">
12 some text...
</div>
<button onclick="document.getElementById('editable').focus();" >Click me</button>
On JSFiddle: http://jsfiddle.net/QKUZz/