Get XY coordinates in the text area

Is there any good jQuery / JS solution to get the absolute carriage position in the text area (given in X / Y coordinates or top / left coordinates).
The jQuery keyDown function's native Event object gives the x / y coordinates of the cursor, and I want something like this to work on the working caret.

My goal is to add a floating HTML element that will be positioned relative to the working position of the caret, so I need to somehow get its position.



I need a solution for working with TextArea elements, but a general solution for any editable html element will be even better!

+3
source share
4 answers

jQuery - , !

+5

, <textarea> <div contenteditable="true">, , .

+5

textarea meteor-autocomplete, 8 GitHub. , , textarea-caret-position .

- http://jsfiddle.net/dandv/aFPA7/

enter image description here

<div> , <textarea>. div a <span> . , faux div.

, , . GitHub @.

+4

http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/

, :)

$('textarea').click(function (e){
    var   x =  e.pageX;
    var   y =  e.pageY;
    //int of top position
    //remember u need absolute position to calculate parents,grandparents to find true                    
    // position from body tag to whereever textarea might be (html) wise
    var tx = parseInt($(this).css('left'));
    var ty = parseInt($(this).css('top')); 
    var fx = x-tx; //final x
    var fy = y-ty; // final y
    console.log('X=> '+fx);
    console.log('Y=>'+fy);
});

NOTE. Perhaps I mixed the x and y axes on the top and left because I'm dyslexic and it's hard to remember such a simple tax :)

I think this can give you the page coordinates, so with that in mind, take textarea(absolute) offeseTop and Left from x and y, then you have :).

-6
source

Source: https://habr.com/ru/post/1793965/


All Articles