0

I have some divs in a table like this one:

<div contenteditable="true"
     onfocus="document.execCommand('selectAll',false,null)">Something</div>

When focusing a div by clicking it, it all works fine, the whole text is being selected.

The problem is that I want the same behaviour when navigating between divs by tab. As it is, navigating by tab just lets me edit the div without selecting the text.

How can I achieve that?

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Dragos
  • 776
  • 8
  • 32

2 Answers2

3

Execute command after element is focused, not on focus. To delay it, you can use a timeout, this will put callback in event queue, executing it after element is focused.

Your code should be (without using any inline script but jQuery as tagged in question):

$('div[contenteditable]').on('focus', function() {
  setTimeout(function() {
    document.execCommand('selectAll', false, null)
  }, 0);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable>Something</div>
<div contenteditable>Something New</div>
Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

You can use the below function to select all the content of a content editable div.

 const onSelectText = (event) => {
    if (window.getSelection) {
      const selection = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(event.currentTarget);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  };
.select-text{
width:200px;
border:1px solid black;
padding:15px;
}
<div class="select-text" contentEditable="true" onClick=onSelectText(event)>Hello, welcome to my world</div>

content editable div.