In this post I am going to explain about a trick that would help us to resolve a focus and select issue, which I recently found in Google Chrome (version 29.0.1547.76 m) and Firefox (version 23.0.1). This is a browser-specific issue and it’s kind of weird that it didn’t occurred in
Internet Explorer 10
Issue
Let’s say we have a requirement like as soon as a user focus anywhere
inside a textbox, it would automatically select the whole text present
inside the textbox. For this demo, our HTML markup is very simple. We
have input text box which has a value already set for the demo purpose
only.
<input id='myInput' type="text" value="This is a sample text." /> |
Now, we can achieve the above requirement using the power of jQuery like:
JS:$('#myInput').focus(function () { $(this).select(); }) |
This is a quite a simple code but still for a wider audience, let me explain about it in few lines:-
- Code in the first line above is used to attach a focus event handler to the input text-box with ID as myInput
- Code in the second line is used to select the entire text field using the .select() method. Actually, here we are triggering the “select” JavaScript event manually, by applying the .select() without an argument.
Expected Result:
Now our expected result is as soon as user focus anywhere inside a textbox, it would automatically select the whole text. With the jQuery code above, it works fine in other browsers but not in Chrome and Firefox. In Chrome/Firefox, as soon as user focus anywhere inside a textbox the whole text get selected and then un-selected. It happens very fast, so might even thinks that nothing happens at all. I have created a demo for it, which you can test and see for yourself.
Now our expected result is as soon as user focus anywhere inside a textbox, it would automatically select the whole text. With the jQuery code above, it works fine in other browsers but not in Chrome and Firefox. In Chrome/Firefox, as soon as user focus anywhere inside a textbox the whole text get selected and then un-selected. It happens very fast, so might even thinks that nothing happens at all. I have created a demo for it, which you can test and see for yourself.
Demo:
- Demo on jsFiddle #1
( Here’s a demo which demonstrate the issue. )
Trick
The trick here to resolve this issue is to prevent the default action of the "mouseup" JavaScript event, by using the following code:
JS:
$('#myInput').mouseup(function (e) { e.preventDefault(); }); |
Demo:
- Working Demo on jsFiddle #2
( Getting the expected result now. )
This happens since in some browsers mouseup event is raised before the focus event but in Chrome or Firefox mouseup event is raised after the focus event causing the “Focus and Select” issue. But by preventing the default action of mouseup event from triggering, we make sure nothing like that happens in Chrome or Firefox too.
That’s it! If you have any comments or suggestion about this post, I would really appreciate it.
Happy Coding
Happy Coding