I needed to automatically focus a contenteditable div after the user had been granted permission to make edits - that part was pretty easy, however the cursor ends up at the start of the text in the div. Unacceptable!
I did some googling and the most upvoted answer on Stackoverflow was from 2010 ... surely there's a easier way to do it now, twelve years later! The key is just looking through the nice MDN docs on the Selection API.
Breaking down the JavaScript
const div = document.querySelector('div > div:nth-child(2)');
div.focus();
First, store the DOM element you wish to put the cursor in, and call focus()
- this will put the cursor at the beginning of the text in the element. You'll need that DOM element again in just a moment.
const selection = window.getSelection();
Next, get a selection object!
selection.selectAllChildren(div)
selection.collapseToEnd();
Finally, call selectAllChildren(div)
passing in your DOM element. Reading selectAllChildren may make you think of child HTML elements (it was my first thought!) but this will also include all the text contained in the node. The call will also deselect anything already selected on the page.
The next call, collapseToEnd will move the caret to the end and the selection will be gone, leaving just the blinking cursor.