How to set and get cursor position in a text area | TinyMCE (2024)

Navigating the Document Object Model (DOM) of a page is a powerful skill to have, once it’s mastered. However, it’s not always clear exactly what node within the DOM that a part of the web page rests inside.

Traversing the DOM steps you through the elements of a web page. It’s like following map directions. And like a map, each element of the web page has an address. We can target these addresses – also called nodes – and make changes to the page.

Usually, changes happen in response to customers pressing a button or some other interaction. But what about finding your way when the changes are inside a text area? The text area, in its most fundamental form, lives inside the page DOM, but as text inside it, which means there are text nodes. And if there are nodes, then you can navigate through them like stepping stones. And if you’re navigating through them, you might want to place the cursor position at a specific spot.

But it’s not always a direct path through the DOM, through the textarea element, and to a specific cursor position.

For TinyMCE, a rich text editor that has shown time and again its reliability, this process is made possible (with some limits), using specific APIs. This article explains how it’s done, with some examples.

What’s a cursor position? And what’s a caret?

A cursor is a pointer – the graphical icon that represents the mouse moving around the web page on screen. Sometimes, the “cursor” position is brought up to describe the “caret” position.

A caret is the blinking line that indicates where the next word is going to appear when keydown events (the press of the keyboard) happens. Still unclear? What really matters in this case is the intention – do you want to put the blinking line in a specific place in the text area? Then in that case, you want to set the caret at a specific position.

What you need to set cursor positions

With that goal in mind, what skills and knowledge do you need to set the caret in the right spot? You need to know the following:

  1. Understand JavaScript
  2. Understand Web APIs
  3. Some curiosity about TinyMCE APIs

It’s also important to know the limits. Finding out a specific place in the textarea is difficult. It can also be difficult in TinyMCE's text area.

What you can do is first place the caret at the location you want, and then you can bookmark that location. Then, you can load that location when you need it. That’s the main limit of setting the cursor location – you need to choose the location if you want a specific spot first, save it, and then apply that specific bookmark later on.

Getting the cursor position

While you can set the position using TinyMCE APIs, getting the cursor position coordinates, integers, or a string represents a more difficult challenge. Using the TinyMCE Bookmark Manager API, you can set the cursor position that you want to get, and then bookmark that cursor position. The API saves the location so you can retrieve it later (more on the API in the following procedures).

Setting the cursor position

1. Select content, and then bookmark the position of the content

Using the TinyMCE Bookmark Manager API, you can configure the editor to hold on to the caret position in the form of a selection of content. A selection, also known as highlighting, happens when the browser recognizes that you have pushed the mouse button down, dragged the cursor across content, and then let the mouse button move up again. You can also hold down shift and then move the cursor with the arrow keys on the keyboard to select content. It has the same effect. The TinyMCE bookmarks this location with the Bookmark Manager API, and then loads the selected location later.

2. Set the caret position on newly added content

You can place the caret position if you are adding content into the TinyMCE text area. You can set the caret position to be at a specific index location within a DOM element like <p> or <strong> that you’re adding to the editor. The TinyMCE APIs can target the content you’re adding in and TinyMCE then essentially picks up your cursor, and puts it down at the integer you want. For instance, if you write “<strong>bold text</strong>” to the text area, you can add an API and use it to set an integer of “<strong> [5]” to place the caret on the fifth character of the <strong> element, which is the letter “t” in text.

3. Set the caret position at the end of the text area

The expected behavior of the text area caret is to appear at the beginning, that is, the top left hand corner of the text area. You can set the caret to appear in the lower right of the text area, which is the opposite position to where it ordinarily appears.

How to set the caret position

The first option involves the TinyMCE Bookmark Manager API. To test this out, the tutorial creates a function, and sets the function up to run when a button on the demo web page is clicked.

Set up a TinyMCE demo editor

  1. Create a new index.html file on your workstation.
  2. Sign up for a FREE TinyMCE API key. This key gives you 14 days free access to TinyMCE’s premium plugins. Using the key also prevents domain identification errors showing up in the text area.
  3. Include the following HTML to start up the TinyMCE demo editor:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: "#editor", )}; </script> </head> <body> <h1>TinyMCE Example</h1> <form method="post"> <textarea id="editor"></textarea> </form> </body></html>
  1. For this cursor position test, the rich text editor resides inside a Document Management System. Setting this up requires using the content_style option to target the body element and change the appearance:

<script> tinymce.init({ selector: "#editor", content_style:` body { background: #fff; } @media (min-width: 840px) { html { background: #eceef4; min-height: 100%; padding: 0 .5rem } body { background-color: #fff; box-shadow: 0 0 4px rgba(0, 0, 0, .15); box-sizing: border-box; margin: 1rem auto 0; max-width: 820px; min-height: calc(100vh - 1rem); padding:4rem 6rem 6rem 6rem } } ` }); </script>
  1. Save the changes, and test the index file in the browser. You can also test it by running the index file on your workstation’s local host using a python command or a PHP command:

How to set and get cursor position in a text area | TinyMCE (1)

Configuring the Bookmark Manager API

To test out this API, and see how it works quickly, this tutorial makes use of the Developer Tools console.

  1. With the developer console open (ctrl + option + j on chrome for instance) highlight the content in the editor that you want to bookmark, and return the cursor position to later.
  2. Run the following command to bookmark the cursor position:
let bookmark = tinymce.activeEditor.selection.getBookmark();
  1. Move the cursor away from the bookmarked content. You can remove the highlighted selection, and include some more content in the editor at this stage.

  2. To load the bookmark, run the following command in the developer console:

tinymce.activeEditor.selection.moveToBookmark(bookmark);

With the moveToBookmark method, the editor will return the content set up and selected with the getBookmark command. This is one way to capture the cursor position inside the TinyMCE editor, and then return to it later when you need it.

Setting the cursor position at new elements

For this method, the tutorial sets up an interactive element (a button) and runs the TinyMCE setCursorLocation API command.

  1. Set a button element just after the text area in the demo HTML file:

<body><h1>TinyMCE Example</h1><form method="post"><textarea id="editor"></textarea></form><button></button>
  1. Give the button the id of buttonSelect

<button id=”buttonSelect”></button>
  1. Set up a pair of script tags after the body element of the demo HTML file:

</body><script> </script></html>
  1. Place the following function inside the script tags. This function stars by selecting the active editor Body element :

<script> function selectionCommand() { let editorBody = tinymce.activeEditor.getBody();
  1. Extend the function by using the TinyMCE setContent API to change the editor content

<script>function selectionCommand() { let editorBody = tinymce.activeEditor.getBody(); tinymce.activeEditor.setContent('<p>hello <strong>bold</strong> content</p>');
  1. To set the cursor position in the new content, add to the function a variable, and assign to it the bold, or strong, element set up in the previous step.

    Note: This is one method for selecting the TinyMCE text editor, setting content, and then selecting a specific node within the editor.

<script>function selectionCommand() { let editorBody = tinymce.activeEditor.getBody(); tinymce.activeEditor.setContent('<p>hello <strong>bold</strong> content</p>');Let nodeStrong = tinymce.activeEditor.dom.select('strong')
  1. Add the setCursorLocation API command targeting the variable set up in the previous step (containing the strong tag selection), and set the focus method:

<script>function selectionCommand() { let editorBody = tinymce.activeEditor.getBody(); tinymce.activeEditor.setContent('<p>hello <strong>bold</strong> content</p>'); let nodeStrong = tinymce.activeEditor.dom.select('strong'); tinymce.activeEditor.selection.setCursorLocation(nodeStrong[0].firstChild, 2);tinymce.activeEditor.focus();}</script>
  1. Add an event listener that’ll be triggered by the button click event, referencing the button added at the beginning of this procedure:

<script>function selectionCommand() { let editorBody = tinymce.activeEditor.getBody(); tinymce.activeEditor.setContent('<p>hello <strong>bold</strong> content</p>'); let nodeStrong = tinymce.activeEditor.dom.select('strong'); tinymce.activeEditor.selection.setCursorLocation(nodeStrong[0].firstChild, 2);tinymce.activeEditor.focus();}var buttonSelection = document.getElementById('buttonSelect');buttonSelection.addEventListener('click', selectionCommand, false);</script>
  1. Save the changes, and then test run the button to set the cursor position:

How to set and get cursor position in a text area | TinyMCE (2)

Setting the caret position at the end of the text area

With the selection.collapse API method, you can move the cursor position to the end of the editor.

  1. Add a second button the the demo HTML file after the button produced in the previous procedure:

<button id="buttonEnd" class="button_style"> Go to the end</button>;
  1. Add a new function to script tags at the end of the demo HTML file:

function endCommand() {}
  1. Use the selection API and the getBody API methods to capture the text area content:

function endCommand() {tinymce.activeEditor.selection.select(tinyMCE.activeEditor.getBody(), true);
  1. Include the collapse API method to move the cursor to the end of the selection range, which is the end of the editor, and then include the focus API:

function endCommand() { tinymce.activeEditor.selection.select(tinyMCE.activeEditor.getBody(), true); tinymce.activeEditor.selection.collapse(false); tinymce.activeEditor.focus();}
  1. Add an event listener to trigger the function when the button is clicked:

var buttonEnd = document.getElementById("buttonEnd");buttonEnd.addEventListener("click", endCommand, false);
  1. Save the changes, and test run the button to move the cursor to the end of the rich text editor:

How to set and get cursor position in a text area | TinyMCE (3)

Setting the cursor position in practice

Depending on what you need in your web page or app, you can use one of the methods available with the TinyMCE API to set the cursor position in your rich text editor.

Next steps could include setting the Bookmark Manager API to run on events in the interface, such as a mouseup event, following a highlight.

Once you have the DOM node selected in the text area, you can be precise, and set the caret to appear at a specific index number within that DOM node. This is the key point to remember – that setting the cursor position on a specific point in the text area needs a specific DOM node to work correctly.

If you’d like to find out more about TinyMCE, and try some of the Premium Plugins, contact us and our customer success team can help you find the rich configuration for your web page or app, and set the cursor position where you need it.

Get your FREE TinyMCE API key today for your app today!

How to set and get cursor position in a text area | TinyMCE (2024)

FAQs

How to set cursor position in TextBox in javascript? ›

createRange(); // Here 'rangeobj' is created Range Object var selectobj = window. getSelection(); // Here 'selectobj' is created object for window // get selected or caret current position. // Setting start position of a Range rangeobj. setStart(startNode, startOffset); // Setting End position of a Range rangeobj.

How do I change the cursor position in textarea? ›

Click in the following input box, scroll with the arrow keys and watch. Use Home, End and Arrows keys or the mouse to change the cursor position.

How to set cursor position in TextBox using jquery? ›

focus(function() { $(this). setCursorPosition(4); }); What would the implementation of that setCursorPosition function look like? If you had a text field with the content abcdefg, this call would result in the cursor being positioned as follows: abcd**|**efg.

How do I find the cursor position in text area? ›

First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.

How do I automatically put the cursor in the text field? ›

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.

How to set cursor position in textarea in HTML? ›

To set the cursor at the end of a textarea:
  1. Use the setSelectionRange() method to set the current text selection position to the end of the textarea.
  2. Call the focus() method on the textarea element.
  3. The focus method will move the cursor to the end of the element's value.

How do I change cursor position? ›

Use the SetCursorPosition method to specify where the next write operation in the console window is to begin. If the specified cursor position is outside the area that is currently visible in the console window, the window origin changes automatically to make the cursor visible.

How to get the cursor position in text javascript? ›

If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.

How to get cursor position in JavaScript? ›

Steps. Step 1 − In step one, we need to define the callback function that performs some activity when the event triggers. Step 2 − In the second step, we will declare a variable and assign it a value using event. clientX property, that returns the horizontal or the X-coordinate of the cursor position.

How to set cursor focus on textbox in angular? ›

find('input[name=headline]'). focus(); element. querySelector('input[name=headline]'). focus();

How to set cursor position in textbox in selenium? ›

3 Answers
  1. import org. openqa. selenium. WebElement;
  2. import org. openqa. selenium. interactions. Actions;
  3. builder. moveToElement(Element, 100, 100). click(). build(). perform();

How to place cursor position at end of text in text input field using JavaScript? ›

To move the cursor to the end of an input field:
  1. Use the setSelectionRange() method to set the current text selection position to the end of the input field.
  2. Call the focus() method on the input element.
  3. The focus method will move the cursor to the end of the input element's value.
Jul 25, 2022

How do I get the cursor to start in text field in HTML? ›

To position the cursor at the beginning of the contents of a TextBox control, call the Select method and specify the selection start position of 0, and a selection length of 0.

Which library function positions the cursor within a text window? ›

Summary. You can make a Windows API (application programming interface) call to a Microsoft Windows DLL (dynamic-link Library) to get and set the current cursor position. The current position can be obtained by using the GetCursorPos function in USER32. DLL.

How do I align text in text area? ›

The default is align=top. With ALIGN=LEFT, the field will float down and over to the current left margin, and subsequent text will wrap around the right hand side of the field. Likewise for ALIGN=RIGHT, the field aligns with the current right margin and, and text wraps around the left.

What is text cursor movement? ›

Cursor movement. Description. The cursor moves from its current position left or right to the next character, or up or down to the next row. For example, if the cursor is located at the end of the first left-to-right part of a mixed sentence: THERE IS_txet lanoitceridib IN THIS SENTENCE.

What is do you use to move the cursor around your text? ›

Moving With Arrow Keys

You should be able to move the cursor freely about the screen by using combinations of the up, down, right, and left arrow keys. Notice that you can only move the cursor across already existing text or input spaces.

How do I limit mouse cursor movement to a specific area? ›

Right-click on the icon to access Lock Cursor Tools' context menu. The first option should tell you the setting that you have chosen, along with a keyboard shortcut. The default hotkey to trigger the lock is Ctrl + Alt + F12. Once you do that, the mouse cursor will be restricted to the selected area, monitor or window.

How do I find the position of a pointer? ›

In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

What are the 3 types of cursor positioning? ›

3 Top Cursor Handling Methods in CICS Screens
  • Using IC Option.
  • Direct Cursor Positioning.
  • Symbolic Cursor.
Jun 29, 2015

How do I change the cursor position in Word? ›

Using a combination of keystrokes can also move the cursor further – e.g. holding down the Ctrl (control) key and pressing the left arrow key will move the cursor left one word. Holding down Ctrl and pressing the up arrow key will move the cursor to the start of each paragraph.

How do I fix the direction of my cursor? ›

Resolution
  1. Click 'Computer' in the bottom left of the screen.
  2. Click 'Control Center' from the pop up menu.
  3. In the 'Hardware' section of the Control Center, select'Mouse'.
  4. In the section entitled 'Mouse Orientation', make sure that the field 'Left Handed Mouse' has an 'x' in the box next to it. ...
  5. Click 'Close'.
Mar 5, 2021

What is a caret position? ›

A caret has a position in the document referred to as a dot. The dot is where the caret is currently located in the model. There is a second position maintained by the caret that represents the other end of a selection called mark. If there is no selection the dot and mark will be equal.

How to set cursor in JavaScript? ›

To set or change the mouse cursor style for an element of your page from script, you can set the element's property element. style. cursor to one of the above values. (Alternatively, without JavaScript, you can use the attribute style="cursor:value;" in that element's HTML tag.)

How do you set focus on a text field? ›

Focus on a text field
  1. HTML. <input id="myTextField" value="Text field." /> < button id="focusButton">Click to set focus on the text field</button>
  2. JavaScript. The code below adds an event handler to set the focus on the text field when the button is pressed. ...
  3. Result. Select the button to set focus on the text field.
Nov 3, 2022

How do you focus on a TextBox? ›

Input Text focus() Method

The focus() method is used to give focus to a text field. Tip: Use the blur() method to remove focus from a text field.

How do I set input to focus? ›

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

How to get cursor position in Selenium? ›

Selenium will right click on your element, which will result in the context menu being displayed at the bottom right corner of your cursor. Once you see the position of the context menu, you will know whether Selenium is clicking on the right element.

How to set cursor focus on textbox in Java? ›

invokeLater( () -> textField. requestFocusInWindow() ); The above code will be placed on the end of the Event Dispatch Thread (EDT) , so it should execute after the window has been made visible.

How do I fix the position of a text box in HTML? ›

Fixed Positioning

You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document. Move Left - Use a negative value for left. Move Right - Use a positive value for left. Move Up - Use a negative value for top.

How do you get the insertion point cursor move to the end of the typing line on a single action? ›

Press Ctrl+End.

[The insertion point moves to the end of the document].

How can we move the cursor to the beginning and end of the line? ›

Moving the cursor on the line
  1. Go to the beginning of a line, and press w. The cursor jumps forward to the beginning of the next word on the line. ...
  2. Typing b is like typing w, except that you go back a word instead of forward. ...
  3. If the cursor is in the middle of a word, typing e moves the cursor to the end of the word.

What moves the cursor to the end of the line? ›

Which key is used to move the cursor to the end of the line? The Home key moves the cursor to the beginning of the current line of typed characters, the End key moves it to the end.

Which key is used to move a cursor to beginning of a line of text? ›

The Home key moves the cursor to the beginning of the current line of typed characters, the End key moves it to the end.

Which of the following key move the text cursor to the beginning of the land? ›

Ctrl + Home Moves the cursor to the beginning of the document. Ctrl + Spacebar Reset highlighted text to the default font.

What function is used to place a cursor position in file? ›

An application can position the file pointer to a specified offset by calling SetFilePointer. The SetFilePointer function can also be used to query the current file pointer position by specifying a move method of FILE_CURRENT and a distance of zero.

Which function is used to move the cursor position in file? ›

seek() method

In Python, seek() function is used to change the position of the File Handle to a given specific position.

Which function is used to move get pointer to a specified location? ›

fseek() is used to move file pointer associated with a given file to a specific position.

How do I control text alignment? ›

Change text alignment

To align the text left, press Ctrl+L. To align the text right, press Ctrl+R.

What are the four types of text alignment? ›

Alignment determines the appearance and orientation of the edges of the paragraph: left-aligned text, right-aligned text, centered text, or justified text, which is aligned evenly along the left and right margins.

How to get the cursor position in text JavaScript? ›

If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.

How to change cursor position in js? ›

To move the cursor to the end of an input field:
  1. Use the setSelectionRange() method to set the current text selection position to the end of the input field.
  2. Call the focus() method on the input element.
  3. The focus method will move the cursor to the end of the input element's value.
Jul 25, 2022

How to get position of cursor in JavaScript? ›

Using event.

clientX property is used to find out the value of the horizontal position or the X-coordinate of the cursor where the event was triggered. It returns a numeric value that specifies the horizontal position of the cursor.

How do I change the cursor position in CSS? ›

Use padding on the input element to adjust the position of the blinking cursor. That will do it. Adjust the position either by increasing or decreasing the padding.

How do you find the position of an element? ›

Given an HTML document and the task is to get the position of any element by using JavaScript.
...
Some of the methods are:
  1. The getElementsByTagName() Method.
  2. The getElementsByClassName() Method.
  3. The getElementById() Method.
  4. The getElementsByName() Method.
  5. The querySelector() Method.
  6. The querySelectorAll() Method.
Dec 22, 2020

Which library function position the cursor within a text window? ›

Summary. You can make a Windows API (application programming interface) call to a Microsoft Windows DLL (dynamic-link Library) to get and set the current cursor position. The current position can be obtained by using the GetCursorPos function in USER32. DLL.

Top Articles
Latest Posts
Article information

Author: Duncan Muller

Last Updated:

Views: 5561

Rating: 4.9 / 5 (59 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Duncan Muller

Birthday: 1997-01-13

Address: Apt. 505 914 Phillip Crossroad, O'Konborough, NV 62411

Phone: +8555305800947

Job: Construction Agent

Hobby: Shopping, Table tennis, Snowboarding, Rafting, Motor sports, Homebrewing, Taxidermy

Introduction: My name is Duncan Muller, I am a enchanting, good, gentle, modern, tasty, nice, elegant person who loves writing and wants to share my knowledge and understanding with you.