Using focus with setTimeout in jQuery Javascript

jQuery provides a function focus() which can be called up on an element to pull focus on it.

This function can be used to highlight a button/textbox or any other element and is highly useful when making an application more user friendly, for example, by default focussing the username field when login page loads etc..

But sometimes, even if focus() function has been used then also the element is not able to pull the focus.

For example, one such case can be when we display a pop-up with button on blur event of a textbox and we want to have this button in pop-up to be focussed. Here in such a case, focus() function can be called once pop-up is displayed to put the focus on button. This code will work fine, except for the case when user clicks a link which fires the blur of textbox and pop-up gets displayed.

In such a case, the focus will stay at the anchor tag clicked by the user instead of the pop-up button even if we have used focus() on the button.

This can be an irritating experience for the user who may press enter to select the button from pop-up only to realize later that the anchor tag got executed.

One way to avoid this is by using setTimeout function of Javascript in following way:


Important thing to note here is the use of ‘0’ milliseconds in the code. Using setTimeout like this ensures that a new task gets added to the queue of browser Javascript and is executed after 0 milliseconds which ensures that the focus gets applied to our intended element.

This hack can thus serve the purpose ensuring that the focus is always on the element where we intend it to be.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s