Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method for this or if there's an option to get the bookmark position in pixels and then remove it?

Appreciate any insight on this matter!

Answer №1

Great, I've located the information.

To start, you'll need to initialize an instance of the tinymce.Editor class. This can be done like so:

var editor = new tinymce.Editor(); //or another method, such as tinyMCE.activeEditor

Using jQuery, retrieve the position of the TinyMCE widgets:

var tinymcePosition = $(editor.getContainer()).position();
var toolbarPosition = $(editor.getContainer()).find(".mce-toolbar").first();

Now determine the position of the HTML node you are currently editing:

var nodePosition = $(editor.selection.getNode()).position();
var textareaTop = 0;
var textareaLeft = 0;

We have the Y-axis position (via nodePosition.top), now let's find the X-axis position:

if (editor.selection.getRng().getClientRects().length > 0) {
    textareaTop = editor.selection.getRng().getClientRects()[0].top + editor.selection.getRng().getClientRects()[0].height;
    textareaLeft = editor.selection.getRng().getClientRects()[0].left;
} else {
    textareaTop = parseInt($($this.selection.getNode()).css("font-size")) * 1.3 + nodePosition.top;
    textareaLeft = nodePosition.left;
}

The positions of the caret relative to the TinyMCE editor window (textarea) are now stored in

textareaTop && textareaLeft
. Let's find their positions relative to the entire page (browser window):

var position = $(editor.getContainer()).offset();
var caretPosition = {
    top:  tinymcePosition.top + toolbarPosition.innerHeight() + textareaTop,
    left: tinymcePosition.left + textareaLeft + position.left
}

This solution is inspired by the autocomplete plugin for TinyMCE 3 found at here, and has been adjusted to fit my needs in TinyMCE 4.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

The never-ending scrolling problem: Autoscroll refusing to halt - a perplexing conundrum in the world

I'm having an issue with my chat box continuously autoscrolling and not allowing me to scroll up. I know where the problem is, but I'm unsure of how to resolve it. Ideally, I want the chat box to autoscroll while still maintaining the ability to ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

Display modal popup only once the dropdown has been validated, with the validation focusing on criteria other than the dropdown itself

Looking for a way to validate dropdown values. Popup should only show if the dropdown values are selected; otherwise, the popup should remain hidden. Below is the code snippet: <div class="main-search-input-item location"> ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

The functionality of Jquery AJAX is operational, however, the message being displayed appears to

Inside the file changename.php, there is a DIV element: <div id="resultDiv"></div> Within the same file, PHP code can be found: <?php include_once ('connect.php'); if(isset($_POST['name'])) { $postedname = $_POST[&ap ...

Basic AngularJS framework with minimal external dependencies

I have been searching for an AngularJS skeleton to set up my project, but it seems like all the skeletons I find online require the installation of numerous dependencies through npm and/or bower. Due to security concerns at the firm where I am working on ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

Exploring the depths of design in material-ui

I've just started diving into material-ui and decided to create a simple app in the SandBox: https://codesandbox.io/s/eager-ride-cmkrc The styling using jss is a bit unusual for me, but with your help on these two exercises, I'm sure I'll ...

Creating a Loopback API that seamlessly integrates with Ember.js

Exploring the use of Loopback to create an API that communicates with Ember. Ember expects JSON data to be enclosed in 'keys', such as for an account: { account: { domain: 'domain.com', subdomain: 'test', title: ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Guide to generating a div element with its contents using JSON

On my webpage, there is a button that increases the "counter" value every time it's clicked. I am looking to achieve the following tasks: 1) How can I generate a json file for each div on my page like the example below: <div class="text1" id="1" ...

Is there a way to define the route path when using MemoryRouter in Jest without using location or history objects?

Apologies if this question has already been asked before. I have a query regarding MemoryRouter in React. I am able to set initialEntries and initialIndex to customize "location" and "history", but the "match" parameter does not update as expected. It is ...

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

I am having trouble printing because of document.write

Whenever I use javascript to create a document with document.write I include an iframe element then I try to print the contents using iframe.print() but nothing happens - no error message and no print dialog box. How can I successfully initiate a print ...

Attempting to grasp the intricacies of HTML5/JS video playback quality

I've been diving deep into research on this topic, but I can't seem to find a straightforward answer to my specific query. My main focus is understanding the inner workings of how video players transition between different quality settings (480p, ...

Having trouble implementing server-side rendering with Styled-Components in Next JS

I attempted to resolve my issue by reviewing the code and debugging, but unfortunately, I couldn't identify the root cause. Therefore, I have posted a question and included _document.js, _app.js, and babel contents for reference. Additionally, I disa ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

Issue encountered while creating a token in a JavaScript Chrome extension and attempting to validate it on a backend Node.js server

Trying to create a token within a chrome extension and utilizing it to authenticate requests to the backend server has proven challenging. While successfully generating a token on the front end, encountering an error when verifying it with the google-auth- ...