'Contenteditable div with selectAll on focus not working entirely
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?
Solution 1:[1]
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>
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Ipsita Priyadarsini |