1

Assuming a regular <input type=text> text-box with data in it.

Is it possible to detect (via JavaScript) the position of the text-coursor inside that text-box?

I am able to detect an ARROW LEFT or ARROW RIGHT keydown event - but how to detect the cursor location?

Why I need this:

I have a dynamic text-box here: http://vidasp.net/tinydemos/dynamic-textbox.html
It works great, however there are two scenarios that I would like to fix:

  1. when the cursor is at the beginning of the text-box and the user presses BACKSPACE
  2. when the cursor is at the end of the text-box and the user presses DELETE

(In both cases, the text-box must contain data for the effect to be observable.)

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385

2 Answers2

3

I've done quite a lot of work on this. The following works in all major browsers (including IE 6) for text <input>s and <textarea>s and will work in all situations, including when there are leading and trailing spaces (which is where many solutions, including a-tools, fall down). There's some background to this code in this question: IE's document.selection.createRange doesn't include leading or trailing blank lines

You can also get the following as part of a jQuery input/textarea selection plug-in I've written that is as yet undocumented: http://code.google.com/p/rangyinputs/

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

var el = document.getElementById("your_input");
var sel = getInputSelection(el);
alert(sel.start + ", " + sel.end);
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Great peace of code :) I incorporated it into my demo: http://vidasp.net/tinydemos/dynamic-textbox.html – Šime Vidas Nov 15 '10 at 16:05
  • With your function it should be a **piece** of cake to accomplish this as well, right? http://stackoverflow.com/questions/4179922/how-to-programmatically-disable-auto-select-on-input-typetext-elements Or is it just possible to get the selection, and not set it (as in remove it)? – Šime Vidas Nov 15 '10 at 19:23
  • @Šime: It's possible to set the selection, and bizarrely in IE it's easier than getting it. I've posted a function to do it a few times on Stack Overflow, for example here: http://stackoverflow.com/questions/3286595/update-textarea-value-but-keep-cursor-position/3288215#3288215 – Tim Down Nov 16 '10 at 09:46
0

yes it's possible.

It's even simpler if you use

http://plugins.jquery.com/project/a-tools

Good Luck :)

edit: please note that the cursor is msot often reffered to as "caret", just FYI ;)

Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36
  • However, the plug-in is pretty heavy - 10k. I was hoping that this feature would come in form of a simple native API method like textbox.getCaretPosition(). – Šime Vidas Nov 15 '10 at 15:48
  • @Šime: It does in non-IE browsers: the `selectionStart` and `selectionEnd` properties of the textarea or inoput. The complication is all for IE <= 8. IE9 implements `selectionStart` and `selectionEnd`. – Tim Down Nov 15 '10 at 16:00
  • The link is down making this answer useless. This is why a link-only solution is discouraged. – PhoneixS Sep 08 '22 at 06:42