PROBLEM: I have a html text input box with some text in it, when user click the input box, I would like to have the caret/cursor appear at the beginning of the input box.
I could move a caret by using setSelectionRange() function, but I don't like the effect that the caret shown at the end of the text input box then moved to the beginning. I would like it to be at the beginning of the input upon shown.
example: http://jsfiddle.net/edh8mkht/1/
HTML
<body>
<input type="text" id="myP" onmousedown="mouseDown()" value="Mozilla" />
</body>
JS
function mouseDown() {
document.getElementById("myP").style.color = "green";
document.getElementById("myP").setSelectionRange(0,0);
}
QUESTION 1:
I use mousedown event to move the caret, but it doesn't move the caret at all, the same thing happens if I use onfocus event. Is that because the caret appears after this two events and making setSelectionRange has no effect?
QUESTION 2:
What's a good way to solve my problem by using javascript? Note: I cannot use placeholder.
Requirements for this to work:
label
(or really any element which can accept a child node)pointer-events
CSS propertyinput
to the label
HTML
<label for="myP" onclick="click();">
<input type="text" id="myP" value="Mozilla" />
</label>
CSS
input#myP {
pointer-events: none;
}
JavaScript
function click() {
var input = document.getElementById("myP");
input.style.pointerEvents = 'auto';
input.style.color = "green";
input.setSelectionRange(0,0);
console.log('click');
}
Important things to consider in this implementation:
input#myP
as opposed to #myP
. Otherwise, the CSS will select both the label
and the input
in some browsers if the for
attribute is specified.setSelectionRange
call. I'd have to do some research to figure out why that is.