How to re-focus to a text field when focus is lost on a HTML form?

ohho picture ohho · Apr 9, 2010 · Viewed 32.5k times · Source

There is only one text field on a HTML form. Users input some text, press Enter, submit the form, and the form is reloaded. The main use is barcode reading. I use the following code to set the focus to the text field:

<script language="javascript">
    <!--
            document.getElementById("#{id}").focus()
    //-->
</script>

It works most of the time (if nobody touches the screen/mouse/keyboard).

However, when the user click somewhere outside the field within the browser window (the white empty space), the cursor is gone. One a single field HTML form, how can I prevent the cursor from getting lost? Or, how to re-focus the cursor inside the field after the cursor is lost? thx!

Answer

bobince picture bobince · Apr 9, 2010

Darin's answer is right, but doesn't work in Firefox. If you want to steal focus back in Firefox too, you have to delay it until after the event:

<input onblur="var that= this; setTimeout(function() { that.focus(); }, 0);">

Or, better, assigned from JavaScript:

<script type="text/javascript">
    var element= document.getElementById('foo');
    element.focus();
    element.onblur= function() {
        setTimeout(function() {
            element.focus();
        }, 0);
    };
</script>

But, I would strongly advise you not to do this. Clicking outside a text box to remove focus from that text box is perfectly normal browser behaviour, which can be of legitimate use (eg. to set search point for ctrl-F, or start a drag-selection, etc). There's very unlikely to be a good reason to mess with this expected behaviour.