I am creating a dropdown while typing in a textarea. How can I get the position of the typed letter given a keyup event?
Asked
Active
Viewed 1,335 times
2
-
https://github.com/component/textarea-caret-position – Amadan May 26 '15 at 01:53
-
Can you elaborate on what you mean by position? Like the x and y coordinates of the character itself? Or the index of the character in the string in the textarea? – Danny Delott May 26 '15 at 02:12
-
Sorry, I meant the x and y coordinates on the screen, so I can position the dropdown in the right place. – Some Guy May 26 '15 at 05:34
-
That's tricky! I suggest you to use the attribute contenteditable instead of using an textarea. Using a div with contentediable you can wrap the last typed character into a span and get its offsetTop and offsetLeft to place your dropdown – João Mosmann May 26 '15 at 20:47
2 Answers
2
Greg's answer seems to work. But if you want a more simpler way to get it, you can access the selectionStart
property of the textarea.
For example
var myTextArea = $("#mytextarea");
myTextArea.keyup(function () {
console.log("The last typed character is at: ", myTextArea.get(0).selectionStart - 1);
});

João Mosmann
- 2,884
- 19
- 25
1
var oldValue = '';
var keyup = function() {
var value = document.getElementById('myTextArea').value;
for(var i=0; i<value.length; i++) {
if(i >= oldValue.length) {
// letter typed at end
oldValue = value;
return; // not really necessary since we should be at the end of the loop anyway
} else if(value.charAt(i) !== oldValue.charAt(i)) {
// letter typed at i
oldValue = value;
return; // no need to keep searching
}
}
// no new letters typed
}

Greg
- 1,225
- 3
- 16
- 35
-
Sorry, I meant the x and y coordinates on the screen, so I can position the dropdown in the right place. – Some Guy May 26 '15 at 05:34
-
Ah that's tricky. You'd need the pixel width of each character in the font you're using, and you'd likely run into problems across different browsers. I'd seriously consider doing something simpler. Most people just align the dropdown with the input box. – Greg May 26 '15 at 12:08
-
You could also try using something like http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – Greg May 26 '15 at 12:10