I'm developing a small application that consists on a set of text inputs, and each one will fit only one character, and all inputs together should behave like one. So, when a input is filled with a character, the next input should be highlighted, behaving like the input's caret. In the same manner, when you empty an input, it should behave like a common character deleting, and the previous input should be highlighted.
You can see my work here: https://codepen.io/Vitaozim/full/vqaRQY
Sample here:
Here's how I've done it:
- Whenever any of the input elements if focused, its whole content is highlighted, to make sure any input it receives changes its whole value.
Whenever the
input
event is triggered in any of the input elements, one of these may happen:- If the input's new value is not blank, the next input element is focused. If it receives a value with more than 1 character, the code will trim the string and leave only the last character.
- Else, the value is programatically changed to one single space, and the previous input element is focused. The value is changed to one single space so that whenever that input is focused again, there will be some content to be highlighted and then deleted, triggering the "backspace" condition.
The problem is, it works perfectly on the following browsers:
- Chrome for Mac and iPhone
- Safari for Mac and iPhone
- Firefox for Mac, iPhone and Android
But it's buggy on Chrome for Android. I tested it in many different devices. The "backspace simulation" bugs and the input's value isn't highlighted on focus.
I've made some tests, and I noticed that if I set the selection after a setTimeout
of 100ms, it works. It's like i'm overriding the browser's default behavior... But that's still an really odd behavior, because it only happens on the "backspace" simulation. Any other situation where the input is focused doesn't have this bug.