Caret position in pixels in an input type text (not a textarea) [duplicate]
Asked Answered
O

6

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.

Ode answered 12/11, 2012 at 16:28 Comment(3)
Have you checked this out? #6931078Deedee
This question is an exact duplicate of Get cursor or text position in pixels for input element (that is, a one line input, <input type="text">), not of getting the pixel coordinates of the caret in text boxes (aka <textarea> elements).Schechter
The incredibly lightweight and robust textarea-caret-position Component library now supports <input type="text"> as well, rendering all existing answers obsolete. Demo at jsfiddle.net/dandv/aFPA7Schechter
S
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.

Seve answered 15/11, 2012 at 16:33 Comment(6)
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.Ode
@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. :)Seve
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 principleOde
@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.Seve
plus one for interesting solution.Naji
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 Component library to support <input ype="text"> as well. Demo at jsfiddle.net/dandv/aFPA7Schechter
N
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

Nez answered 20/11, 2012 at 8:39 Comment(7)
Really clever solution. However you just come out a bit too late into the game. thanksOde
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) ...Nez
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.Seve
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.Seve
+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.Nez
@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.Seve
I've updated the incredibly lightweight and robust textarea-caret-position Component library to support <input ype="text"> as well. Demo at jsfiddle.net/dandv/aFPA7Schechter
N
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.

Nina answered 19/11, 2012 at 19:58 Comment(0)
P
2

Similar questions covering your question:

Pendley answered 20/11, 2012 at 14:1 Comment(1)
I've updated the incredibly lightweight and robust textarea-caret-position Component library to support <input ype="text"> as well. Demo at jsfiddle.net/dandv/aFPA7. All answers are now obsolete.Schechter
N
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! :)

Naji answered 19/11, 2012 at 18:35 Comment(3)
Creative solution, but kind of overkillLocomotor
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.Naji
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 Component library. I've just updated it to support <input type="text"> as well. Demo at jsfiddle.net/dandv/aFPA7Schechter
R
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

Revival answered 18/11, 2012 at 23:54 Comment(5)
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)Nez
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.Seve
@MikeD: or entering wwwwwwwww or mmmmmmmm for that matterSeve
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)Nez
I've updated the incredibly lightweight and robust textarea-caret-position Component library to support <input type="text"> as well. Demo at jsfiddle.net/dandv/aFPA7. It supports anything you'll throw at it, wwww or iiii.Schechter

© 2022 - 2024 — McMap. All rights reserved.