Some things in the specs have behaviours that browser makers are required to adhere to. But other areas are a bit gray, where there is no definite guidance on implementation, so sometimes the behaviour is different from browser to browser.
Below you’ll find four screencasts showing the behaviour of different browsers when using this method. In these brief videos, I’ll be showing you what happens using this JS Bin demo, which you can see embedded here, and which you can test yourself:
Note: The goal here is to make the text in the field selectable when focusing with the mouse, while still allowing the user to deselect and edit the text, should the need arise. Focusing by tabbing into the field will always select the full text, regardless of the presence of the
What happens in Chrome?
- When the cursor is clicked (focused) into the text field, the text is momentarily all selected.
- It then quickly deselects, allowing the user to type at the location clicked within the field.
(The same behaviour occurs in the latest Safari on OSX and Windows 7.)
Notice the different behaviour in Firefox:
- The first click into the text field does exactly what Chrome did (momentary select then deselect and prepare to type).
- The second time you click into the text field, however, all the text is selected and it stays that way.
- Subsequent clicks alternate between nullifying the selection and keeping the selection.
In IE11, the behaviour seems to be more sensible:
- All the text is selected and stays selected each time you click into the field.
- You can choose to deselect inside the field to edit the text (which, for some reason, wasn’t working in the “edit” view in JS Bin in IE11).
- Exact same behaviour as IE11, including the ability to deselect and edit inside the field (but no bug in JS Bin).
What’s the Solution?
If you noticed in the code, I’m using the
onfocus event to trigger the
select() method on the input. A quick Google search turned up this StackOverflow thread, where the top-voted answer recommends using the
onmouseup event instead of
onfocus to overcome the problem of the text instantly deselecting.
The problem with this solution, however, is that if you try to deselect the text inside the field, it fails and instead just keeps selecting the full text over and over again (unless you use your keyboard to edit the text, which works fine). This is pointed out in this 2008 bug report. That bug’s status is set to “ExternalDependency”. I’m not completely sure what that means, but maybe someone familiar with those terms can let us know.
The truth is, I’m not so sure this is a bug since I don’t think there is a requirement for how this should be handled. It is annoying to see this difference in implementations, since it is logical that we as developer would prefer to see the same behaviour across the board.