When creating an element such as an online text editor, there is a cursor which shows the current position if you were to type something in or insert an object such as an image.
When working with something such as an online text editor, you want the cursor to maintain its position after clicking on elements such as a button to make the text bold or italic or any other function.
In order to do that, we need to create a custom function.
So this is what we do below.
So the function, setCurrentCursorPosition() sets the cursor position, so that we can maintain its current position when a button such as to make bold text is clicked.
We create a variable, range, which allows us to get a full range of the document.
The variable, sel, selects the current element, which is the div tag with the attribute contenteditable.
The variable, currentNode, gets the current node in focus (where the cursor lies).
To set the cursor (so that it maintains its current position even though a button is pressed), we use the range.setStart() function. Into this function, we pass in 2 parameters, the first being the current node and the second being the column position of this node.
sel.focusNode gives us the current node.
currentNode.textContent.length gives us the column position of the cursor within this node.
We then have our bold button of which we give an onclick() function of setCurrentCursorPosition() to in order to allow the contenteditable div element to have the cursor maintain its position even after a button is pressed to allow for bold text.
We then have our contenteditable div element.
We show this below so that you can test this out.
You see that after clicking the bold button, the cursor maintains its position and doesn't jump to some other part in the element.