When clicking on an input with some text inside, normally the browser places the cursor/caret where you clicked within the text (beginning, end, in-between letters, etc). However, clicking the very top edge of the input always places the cursor at the beginning of the text, and clicking the bottom always places it at the end. I have to imagine this was intentional. It's consistent across all browsers. But it can easily be misleading/annoying when you go to click at the end of the text expecting to continue writing, but click just slightly too high and find the cursor at the start.
Video example: https://i.sstatic.net/VkNGA.jpg
I've seen plenty of answers addressing how to force the cursor to the end of the text in response to a focus event or some other trigger. However, I didn't find any that addressed only forcing the cursor to the end if that top edge is clicked. As far as I could tell there's no way to discern a top-edge click from a genuine click on the beginning of the text using either the click
or focus
events.
It'd also be great to know just out curiosity why this is the default behavior in the first place.
I have used the internet for YEARS now and have never noticed this. Oblivious.
If you're looking to force the cursor (or caret depending on where you're from) to the end when the user clicks at the top of the input, I would use a strategy of comparing the coordinates of the click to coordinates of the bounds of the input on the click...
handleTestClick = (event) => {
// get the coordinates of the top edge of the input
// from https://stackoverflow.com/questions/442404
const rectTop = event.target.getBoundingClientRect().top;
// then get the coordinates of the click
// from https://stackoverflow.com/questions/23744605
const click = event.clientY;
//test whether the click is close enough to the top to trigger cursor to beginning
if(click - 5 <= rectTop) {
this.moveCursorToEnd(event.target);
}
}
// taken from https://davidwalsh.name/caret-end
// which draws from https://stackoverflow.com/questions/3356770
moveCursorToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
Hope this is helpful or that it gets you on the right track!