Recently there was a discussion in Slack about this issue, which is a common problem unrelated to Elm.
Browsers move the cursor to the end of the input field when the value of an input field is overwritten with a value different from the present value.
A possible fix is to save and restore the position of the cursor (aka caret) while updating the input field with something like this:
const caretPositionBefore = this.inputNode.selectionStart;
this.inputNode.value = newValue;
this.inputNode.setSelectionRange(caretPositionBefore, caretPositionBefore);
So I created a custom element that does this automatically.
You can find a demo here: https://ellie-app.com/hqgbZ6Qg55Ca1
To use this custom element from Elm is necessary to:
- Copy the necessary JavaScript available in the Ellie
- Use
Html.node "custom-input"
instead ofHtml.input
- Use
Html.Attributes.attribute
when changing certain attributes likevalue
andplaceholder
instead of changing them directly withHtml.Attributes.value
andHtml.Attributes.placeholder
I’m not an expert on custom elements so probably there are better solutions or possible imrpvements.
Few things are not done yet, for example, proper support of dynamically changing style.
This solution can be probably used also with other frameworks, like React, etc. that suffer from the same issue
Note that changing the value of the input field while the user is typing is, in general, a bad UX. So be sure to assess the quality of the UX. My use case is a date input field with the pattern “YYYY / MM / DD” that gets over imposed to the value.