27

UPDATE: duplicate of Get cursor or text position in pixels for input element.

TL; DR - use the incredibly lightweight and robust textarea-caret-position Component library, which now supports <input ype="text"> as well. Demo at http://jsfiddle.net/dandv/aFPA7/


Is there a way to know where the caret is inside an HTML text field?

<input type='text' /> 

I would like to position in pixels (and reposition) a div depending on the position of the caret.

Note: I don't want to know the position in characters or in a <textarea>. I want to know position in pixels in an <input> element.

Community
  • 1
  • 1
Zo72
  • 14,593
  • 17
  • 71
  • 103
  • Have you checked this out? http://stackoverflow.com/questions/6930578/get-cursor-or-text-position-in-pixels-for-input-element – Karlth Nov 15 '12 at 16:01
  • This question is an exact duplicate of [Get cursor or text position in pixels **for input element**](http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field) (that is, a one line input, ``), not of getting the pixel coordinates of the caret in text boxes (aka ` – Dan Dascalescu Apr 30 '14 at 07:59
  • 1
    The incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library now supports `` as well, rendering all existing answers obsolete. Demo at http://jsfiddle.net/dandv/aFPA7 – Dan Dascalescu May 02 '14 at 12:37

7 Answers7

18

Using an invisible faux element

You can accomplish this by using an absolutely positioned invisible (using visibility not display) faux element that has all the same CSS properties as your input text box (fonts, left borders and left padding).

This very short and easy to understand JSFiddle is a starting point how this script should be working.
It works in Chrome and Firefox as is. And it seems it should be working in IE9+ as well.

Internet Explorer 8 (and down) would need some additional code to get caret position from start of text within input text box. I've even added a meter at the top to show a line every 10 pixels so you can see whether it measures correctly or not. Mind that lines are at 1, 11, 21,... pixel positions.

What this example does it actually takes all the text in text box up to caret position and puts it inside the faux element and then measures its width in pixels. This gets you offset from left of text box.

When it copies text to faux element it also replaces normal spaces with non-breaking ones so they actually get rendered otherwise if you'd position caret right after space you'd get wrong position:

var faux = $("#faux");
$("#test").on("keyup click focus", function(evt) {
    // get caret offset from start
    var off = this.selectionStart;

    // replace spaces with non-breaking space
    faux.text(this.value.substring(0, off).replace(/\s/g, "\u00a0"));
});​

Mind that faux's right dimensions

  • padding
  • border
  • margin

have been removed in order to get correct value, otherwise element would be too wide. Element's box has to end right after the text it contains.

Caret's position in pixels from start of input box is then easily gotten from:

faux.outerWidth();

The problem

There is one problem though. I'm not sure how to handle situation when text within text box is scrolled (when too long) and caret isn't at the very end of text but somewhere in between... If it's at the end then caret position is always at maximum position possible (input width less right dimensions - padding, border, margin).

I'm not sure if it's possible to get text scroll position within text box at all? If you can then even this problem can be solved. But I'm not aware of any solution to this...

Hope this helps.

Community
  • 1
  • 1
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • I think your answer is super. I will tag it as the correct one shortly (just giving other people a chance to answer). The only reason why I won't tag it just yet, it's because it seems quite hard to do and I would love to hope that there is a simpler solution. – Zo72 Nov 16 '12 at 09:59
  • @Zo72: Yes no problem. There're still 6 days for the bounty to expire and in the meantime somebody can come up with some alternative solution although I doubt there is one. And my solution isn't as hard as it may seem. You can also see from the code provided that it's rather super simple... Let's see for others. I'd like to see alternatives myself as well. :) – Robert Koritnik Nov 16 '12 at 10:14
  • I am doubting that too. However what bothers me is that the browser knows where the cursor is (because it's making it blink) so it should really be much much easier. At least in principle – Zo72 Nov 16 '12 at 16:04
  • 2
    @Zo72: **Not really.** It's not browser's responsibility to render blinking caret. That's OS GUI functionality. Browser merely displays system text box. Blinking is then done by the operating system and its GUI configuration and functionality. Input boxes may still be rendered by browsers though although I think caret is up to OS functionality. – Robert Koritnik Nov 16 '12 at 16:24
  • 2
    plus one for interesting solution. – n.podbielski Nov 19 '12 at 18:25
  • 3
    The problem @RobertKoritnik mentioned can be solved by adjusting the caret position with `element.scrollLeft`. I've updated the incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library to support `` as well. Demo at jsfiddle.net/dandv/aFPA7 – Dan Dascalescu May 02 '14 at 12:21
4

Elaborating on my comment above, I guess the following should work.

To show the principle I omitted formatting, so element (id="spacer") color may needed to be set to #FFFFFE, maybe some pixels of leading space added etc ... but the carret will move proportionally now - provided that id's test and spacer use the same font.

Of course we don't know the distance in [px] as asked, but we are able to position content (a carret in this case) fully in line with the width of a proportional font, so if that's the ultimate goal (like mentioned in OP line 3), then .... voi lá!

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            function adjust()
            {
                document.getElementById('spacer').innerHTML=document.getElementById('test').value;
            }
        </script>
        <p>
            <input name="test" id="test" type="text" onkeyup="adjust()" /> Test <br />
            <span id="spacer"></span>^here
        </p>
    </body>
</html>

Update:

<span id="spacer" style="color: #FFFFFF"></span>

this will make the spacer invisible on a white background, but does not yet prevent the user from highlighting the spacer text by selecting the span element. Leaves the task of making the spacer unselectable - there's a good solution here

Community
  • 1
  • 1
MikeD
  • 8,861
  • 2
  • 28
  • 50
  • Really clever solution. However you just come out a bit too late into the game. thanks – Zo72 Nov 20 '12 at 17:49
  • better late than never ... as long as it works ... I tried to focus on what you wanted to achieve (to position) rather than what you thought you needed to achieve it (a px measure - which QED is not necessarily the same) and so came up with a surprisingly light answer (IMHO) ... – MikeD Nov 20 '12 at 18:02
  • This is basically **the same solution that I provided but with lesser functionality**. I've deliberately left the faux `div` visible, so one can see what's going on. I did say that it had to be hidden and I could as well position it underneath the `input`. And your solution also doesn't work when users would enter spaces into `input` neither would it work when they'd reposition caret using arrow keys within input. So all in all: **this is just a small subset of my solution**. With the exception that I've used jQuery and you've used Javascript + DOM manipulation directly. – Robert Koritnik Nov 22 '12 at 13:26
  • 1
    BTW: Hiding your `span` using `visibility` would be a much better choice because **1.** you'd avoid background conflicts (think of images) as well as **2.** additional scripts to prevent selection. Invisible elements can't be selected. Why complicate things when you can avoid them. **Simplicity rules**. – Robert Koritnik Nov 22 '12 at 13:28
  • +1 for visibility; for the rest ... yes our 2 answers have a lot in common (except jQuery) and we both refined ours over time (my starting point was my comment/speculation added to another post above). Your response got accepted - good so! So if you think my answer doesn't add value please vote me down or vote to have it deleted. – MikeD Nov 22 '12 at 14:30
  • @MikeD: I surely won't. :) Don't be silly. I just wanted to point out certain facts, because Zo72 seemed to be impressed by your answer and I was asking myself why since it partially uses my solution anyway. I wasn't trying to dismiss your answer even though it may seem that way. Sorry about that. – Robert Koritnik Nov 22 '12 at 16:06
  • 2
    I've updated the incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library to support `` as well. Demo at jsfiddle.net/dandv/aFPA7 – Dan Dascalescu May 02 '14 at 12:22
2

You could use <span contenteditable="true"></span><input type="hidden" />. That way you can use window.getSelection() with getRangeAt and getClientRects to get the position. This should work with most modern browsers, including IE9+:

function getCaret() {
    var caret = caret = {top: 0, height: 0},
        sel = window.getSelection();
    caret.top = 0;
    caret.height = 0;
    if(sel.rangeCount) {
        var range = sel.getRangeAt(0);          
        var rects = range.getClientRects();
        if (rects.length > 0) {
            caret.top = rects[0].top;
            caret.height = rects[0].height;
        } else {
            caret.top = range.startContainer.offsetTop - document.body.scrollTop;
            caret.height = range.startContainer.clientHeight;
        }
    }
    return caret;
}

(Keep in mind the project I pulled this from is targeting Mobile Safari, and uses one large contenteditable view. You may need to tweak it to fit your needs. It's more for demonstration purposes how to get the X and Y coordinates.)

For IE8 and below IE has a proprietary API for getting the same information.

The tricky part is making sure that your element only allows plain text. Specifically with the paste event. When the span looses focus (onblur) you want to copy the contents into the hidden field so it can be posted.

Luke
  • 13,678
  • 7
  • 45
  • 79
2

Similar questions covering your question:

Community
  • 1
  • 1
Jan Pfeifer
  • 2,854
  • 25
  • 35
  • 1
    I've updated the incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library to support `` as well. Demo at jsfiddle.net/dandv/aFPA7. All answers are now obsolete. – Dan Dascalescu May 02 '14 at 12:29
1

What about canvas 2D? It has API for drawing an measuring text. You could use that. Set same font, font-size and you should be able to measure width of string from text box.

      $('body').append('<canvas id="textCanvas" width="100px" height="100px">I\'m sorry your browser does not support the HTML5 canvas element.</canvas>');
      var canvas = document.getElementById('textCanvas');
      var ctx = canvas.getContext('2d');
      ctx.measureText(text);
      var width = mes.width;

I used this kind of solution to acquire width of some text to draw it in WebGL. I worked just fine but I never tested this what going to happen when text is to big for canvas context, thought i think it will be fine because it is API for measuring text. But ho knows you should totally check it out! :)

n.podbielski
  • 595
  • 6
  • 11
  • Creative solution, but kind of overkill – Andrew Rhyne Nov 19 '12 at 20:18
  • Hello? We are talking about solution for counting pixels in text box. Who needs that? Nevertheless I think that it's much more accurate then any of other solutions here, and code is not complicated to. But is just my opinion. – n.podbielski Nov 19 '12 at 22:35
  • 1
    A demonstrably accurate solution for getting the caret position in pixels, that doesn't instantiate a `canvas` object, is implemented by the incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library. I've just updated it to support `` as well. Demo at jsfiddle.net/dandv/aFPA7 – Dan Dascalescu May 02 '14 at 12:25
0

heres a working example http://jsfiddle.net/gPL3f/2/

in order to find the position of the caret i counted the letters inside the input and the multiplied that value with the size of 1 letter.

and after that moved the div to that location.

<html>
<head>
<style type="text/css">
body { font-size: 12px; line-height: 12px; font-family: arial;}
#box { width: 100px; height: 15px; position: absolute; top: 35px; left: 0px; background: pink;}
</style>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var letter_size = 6;
$("input[type='text']").keyup(function(e) {
    move_size = $(this).val().length * letter_size;
    $('#box').css({'left': move_size+'px'}); 
});
});
</script>

</head>
<body>
<input type="text" />
<div id="box">
/ move 
</div>
</body>
<html>

UPDATE

$(document).ready(function(){
    var letter_size = 6;
    $("input[type='text']").keyup(function(e) {
        $('.hidden_for_width').text($(this).val());
        move_size = $('.hidden_for_width').width();
        $('#box').css({'left': move_size});
    });
});

added a hidden container in wich i insert the value from input . after that i get the width of that container and move my DIV accordingly

Mihnea Belcin
  • 554
  • 3
  • 10
  • doesn't work for proportional fonts .... enter in field string "my bllllllllllllllllll" and see gap becoming bigger & bigger after each time entering letter "l" (lima) – MikeD Nov 19 '12 at 17:15
  • How much is size of one letter? Consider letter like i, m, w having huge width differences. This can only work with mono spaced fonts. – Robert Koritnik Nov 19 '12 at 18:31
  • @MikeD: or entering **wwwwwwwww** or **mmmmmmmm** for that matter – Robert Koritnik Nov 19 '12 at 18:32
  • there are indeed some environments where the real width of a proportional letter in [px] is known (font classes). Perhaps the entered string can be copied on_Change() and displayed below again in a color only slightly different from background to serve as a growing placeholder... (speculating) – MikeD Nov 20 '12 at 07:44
  • 2
    I've updated the incredibly lightweight and robust [textarea-caret-position](https://github.com/component/textarea-caret-position/releases/tag/2.0.0) *Component* library to support `` as well. Demo at jsfiddle.net/dandv/aFPA7. It supports anything you'll throw at it, **wwww** or **iiii**. – Dan Dascalescu May 02 '14 at 12:23
-1
function getCursorPosition (elem) {
  var pos = 0;  
  if (document.selection) {
    elem.focus ();
    var sele = document.selection.createRange();
    sele.moveStart('character', -elem.value.length);
    pos = sele.text.length;
  }
  else if (elem.selectionStart || elem.selectionStart == '0')
    pos = elem.selectionStart;
  return pos;
}​

getCursorPosition(document.getElementById('textbox1'))
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31