views:

70

answers:

3

Hi, 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?

+1  A: 

Try this:

<div style=" border:solid 1px #D31444" contenteditable="true" onclick="document.execCommand('selectAll',false,null)">12 some text...</div>
Danylo Mysak
This would be better done using the `focus` event, because using the click event will highlight everything whenever the user tries to click to position the caret.
Tim Down
Well, probably, but that depends on what the author of the question wants.
Danylo Mysak
A: 

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);
};
Tim Down
A: 

Thank you guys, just what I need, very cool solution indeed.

How would you do a generic function that can be called on any elements without declare anything? Using Tim's code.

runrunforest