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

Prevent drag and drop functionality in QtWebkit

As I work on creating an HTML GUI for my application using Qt's WebKit, everything is going smoothly with one minor issue. I am trying to prevent users from dragging and dropping images from the GUI itself. While I have successfully disabled text sele ...

Encountering an unhandled promise rejection issue with Knex's batchInsert function when attempting to insert arrays larger than 3 elements

I am currently working on an express app and utilizing Knex as the query string builder. During batch insert operations with an array of 1000+ objects, I encountered an error when the array exceeded a certain length. The specific error message is provided ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

Leveraging the power of `.vue` files in modern web browsers that have native support for

Chrome 60 and the most recent version of Firefox, when used with certain flags enabled, have implemented support for import/export directives. I am interested in utilizing .vue files without relying on NodeJS, but I haven't been able to figure out how ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...

Creating an IF statement within a jQuery / Ajax request when using PHP

Does anyone know how to implement an IF statement inside jQuery? I am currently working with two rows of data in a database that have different statuses. My main file for displaying the data is index.php. Here is a snippet from my index.php: $.get("tes ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

Performing jQuery Ajax Request with multiple Form Elements

I have created multiple forms using my php code, as demonstrated below. My issue is that when I try to make a jquery-ajax request, I'm not sure how to reference a specific form. My objective is for the relevant form data to be posted when the submit ...

When using Angular, the onSelectionChange event is not triggered for angular mat-option components

I am working with a mat-form-field that includes both an input field and a mat-autocomplete feature with mat-options. The input field has a (blur) event triggered when it loses focus, while the mat-option has an (onSelectionChange) event triggered when an ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

Utilize an image in place of text (script type="text/javascript")

The vendor has provided me with some code: <a class="sh_lead_button" href="https://107617.17hats.com/p#/lcf/sfrnrskrvhcncwvnrtwwvhxvzkrvzhsd" onclick="shLeadFormPopup.openForm(event)">FREE Puppies</a> <script type="text/javascript" src="htt ...

Finding the way to locate obsolete or deprecated packages in NPM versions

Is there a way to easily identify outdated deep dependencies in the local node_modules folder, separate from the top-level packages? After running the command: npm install with this content in my package.json: "dependencies": { "bluebi ...

Leaflet - Discovering markers already on the map and removing them: A comprehensive guide

I recently started using leaflet for my open source mapping project. You can check it out here: Below is the jQuery code that I used to create markers on the map when clicking on it: map.on('click', onMapClick); function onMapClick(e) { ...

What is the best way to implement this header style with code?

I came across this design from a potential client recently, even though we didn't end up working together. I thought it would be a good exercise to try coding the design for practice purposes. Just to clarify, this is not my original design and I have ...

Can you show me how to achieve a smooth background color transition for a div that takes 2 seconds to complete when it is inserted into the DOM?

On my webpage, I have a list of items that are constantly being updated via a WebSocket connection to the backend. Each time a new item is added to the list, I would like it to be displayed with a background color transition lasting only a brief moment. ...

Adjusting Javascript code to launch a URL in a new window or new tab depending on the user's selection

I seem to be encountering a puzzling issue with a link on my website. When clicked normally, the link opens in a new window. However, if I right-click and select "open in new window" or "open in new tab," it just reloads the same page where the link was cl ...

What is the best way to create vertical spacing between Material UI Grid Paper components?

The spacing of the goal components is not as I would like it to be. This is how they currently appear. https://i.stack.imgur.com/jApzK.png So far, I have attempted setting the display of the Paper selector to flex. Additionally, I experimented with adjus ...

Display a loading spinner with ReactJS while waiting for an image to load

I am working on a component that renders data from a JSON file and everything is functioning correctly. However, I would like to add a loading spinner <i className="fa fa-spinner"></i> before the image loads and have it disappear once the ima ...