I’m trying to find a solution for this problem for a long time now, so I’m going to ask here now.
Start with a normal contenteditable div element, like this one:
<div contenteditable>Edit this text</div>
If you click on the text, you will be able to edit it with the cursor at the position you clicked at.
Now, I don’t want the text to be editable on the first click, and I don’t want to be able to interact with the text at all while the element is not focused. I could achieve this by disabling the div, turning of contenteditable, with CSS or an overlaying element.
I now want the element to be editable again on doubleclick with the exact same behaviour you would expect from clicking the element normally. Let’s use JavaScript and a EventListener for onmousedown
or ondblclick
for that.
Example 1
<div id="wrapper">
<div id="overlay"></div>
<div id="editable" contenteditable>Edit this text</div>
</div>
overlay.ondblclick = () => {
overlay.style.display = 'none';
editable.focus();
};
// use onblur to restore the overlay
This works, BUT the cursor will be positioned at the start of the element. If you don’t use focus()
, you have to click a third time to focus the element.
Example 2
<div id="editable" contenteditable="false">Edit this text</div>
editable.ondblclick = () => {
editable.setAttribute('contenteditable', true);
};
// use onblur to set contenteditable to false again
// additional CSS will prevent being able to interact with the text if not focused
This works, BUT you will select the word at which you are clicking at instead of putting the text cursor there.
This is for a private project, accessability, compatibility, etc don’t matter.
2
Answers
After some more hours of research, I came to this solution:
It is long, complicated, but it works. The API for this is completely messed up in my opinion. I hope this can help someone in the future.
There’s no need for anything complicated, just prevent the double-click action when adding contenteditable while making sure it’s in focus.