Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement.

For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be 1. Similarly, hovering over 'b' should give me 2, and so on for the rest of the characters.

I have found some examples that utilize functions like selectionStart, but they only work when the caret is already at a specific position within the field.

What I really need is a solution that can track the position of the character under the mouse pointer without requiring any click action on the input field.

I have been unable to find any information on how to convert mouse coordinates into corresponding character positions using JavaScript APIs. Any suggestions or ideas would be greatly appreciated.

Update:

My ultimate goal is to automatically move the caret as the user drags over a contenteditable div. I came across a similar question on Stack Overflow, but no satisfactory solution has been provided yet.

Link to caret auto-move: https://stackoverflow.com/questions/12397792/update-caret-position-of-input-and-insert-text-on-drop-event/53660415#53660415

I have also included another example to demonstrate the difference in behavior between native drag and jQuery drag. Currently, I am using jQuery draggable, which does not support automatic caret dragging.

Link to Example on JSFiddle

Answer №1

Jquery: You might want to give the Caret plugin a shot (although I can't guarantee it will meet your requirements). Further information can be found on the jquery page, although it may not be very informative!

Javascript solutions:

After searching for existing solutions, I only came across one potentially adaptable solution for hover/mouseover functionality. The code is not originally mine; I adapted it from a public fiddle by Carlos Delgado. If you hover over the "Show position" text, it will display the cursor position. Additionally, it showcases the usage of selectionStart and selectionEnd to show start and end positions when text is selected. Try this shorter version here (without start/end info).

// JavaScript function to get input selection position
function getInputSelection(el) {
  // Code implementation here...
}

// Event listener for mouseover event
document.getElementById("trigger").addEventListener("mouseover", function() {
  // Code logic here...
  
}, false);
#trigger{background:#ff8890;}
<p>
  Get the cursor position in a textarea or a text input or the selected text.
</p><br>
<textarea id="texto"></textarea><br><br>
<input type="text" id="trigger" value="Show Position" size="10" /><br><br>
<span id="result"></span>

This alternative solution might also be suitable: It displays the position in the console, which could be preferred. Feel free to adapt it as necessary.

// JavaScript code snippet for showing caret position
document.getElementById('showpos').addEventListener('mouseenter', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
<input id="showpos" />

I hope these suggestions prove to be helpful!

Rachel

Answer №2

Below is a function that can be used with mouse move event's pageX and pageY values:

/**
 * This function retrieves the nearest caret position based on provided coordinates.
 * @param x {int}
 * @param y {int}
 * @param doc {Document}
 * @return {[Node, int]} Node containing the caret and its offset within the node. */
function findNearestCaretPosition(x, y, doc=document) {

    // For Firefox
    if (doc.caretPositionFromPoint) {
        let caretPosition = doc.caretPositionFromPoint(x, y);
        if (caretPosition)
            return [caretPosition.offsetNode, caretPosition.offset];
    }

    // For other browsers
    if (doc.caretRangeFromPoint) {
        let range = doc.caretRangeFromPoint(x, y);
        if (range)
            return [range.startContainer, range.startOffset];
    }

    return null;
}

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

Different ways to prevent invalid entries in an input field with type datetime-local

<input type="datetime-local" step="1"> Is there a way to prevent invalid date input? For example, entering a date like "11:11:1111" in the format "mm-dd-yyyy". How can this be addressed using Moment.js? ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...

Offspring element overrides styling of its parent

#popBox{ width:100%; height:100%; position:fixed; left:0; top:0; border-collapse:collapse; background:black; opacity:0.8; display:none; } <table id="popBox"> <tr> <td></td> <td></td> ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

Reboot JavaScript once a day for optimal performance

Is it possible for the JavaScript's ?random to be based on the current date so that it only loads once a day? <script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script> I am asking this question beca ...

RequireJS is timing out while loading the runtime configuration

I keep encountering a load timeout error with my run-time configuration, specifically with common.js. Although I have set the waitseconds value to 0 for files loaded from common.js, the loadTimeout issue persists for common.js itself. index.html <scr ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

MacGyver's innovative Angular mac-autocomplete directive fails to properly auto-complete

I have incorporated the .css and .js files for MacGyver in my HTML document. Additionally, I have added 'Mac' as a dependency in my Angular application. The following code snippet is included in my HTML: <mac-autocomplete ng-model="selected" ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Utilize data attributes for streamlined markup efficiency

I'm facing a challenge with two almost identical animations, the only difference being the positioning of "left vs right". I want to find a way to reuse the same block of code for both .forward and .backward. I have considered using HTML 5 data-attrib ...

Issues encountered while trying to style an unordered list using the table-cell property

I am having trouble formatting the "How it works" section on my website. When the text is too long, the numbers on the left side grow alongside it as shown in number 4. Is there a way to keep the numbers fixed on the left while allowing the text to expand ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...