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?

Answers:

Answer

Try this:

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

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);
};
Answer

The problem with focus event on a div is that it can't fire because it thinks a div should not be editable. Editable contents in the DOM are marked with tabindex in the background, so in order for your div to receive the onfocus event, you need to explicitly declare the div's tabindex property. HTML:

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

That should work with onfocus.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.