How to Maintain the Cursor in its Current Position on a ContentEditable Div Element After Clicking Away on a Button with Javascript


Javascript


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.

Javascript will not keep the cursor in its current position by default after clicking on another element such as a button.

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.

Afterwards, we have javascript code that gives functionality to the bold button.

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.

And this is how to maintain the cursor in its current position in a contenteditable div element after clicking a button in javascript.


HTML Comment Box is loading comments...