In this article I will discuss the need as a developer to use an auto-focus on your XPages. You do this when the end-user needs to type something onto your webpage and should not have to use their mouse to click in the field first.
Introduction
You’ve been there – you go to a website internal or external to your company and you have to login in or type something into the page – the search field or something of that ilk. It is the only field on the whole page and you have to use your mouse to focus on the field – frustrating beyond belief and quite frankly, lazy on the part of the developer. It is a pet peeve of mine when something as simple as one line of code can make a big difference to the first thing a user does on your site.
Can you imagine going to Google.com and having to focus on the field to get started on your search? Stupid idea – or so you would think.
Login Pages
The login page is perhaps the most obvious thing – as the developer you should ALWAYS focus on the username field – it is just lazy not to! It is harder on the user to have to click in the field and they are entering your website with an irritation on their mind already.
So how do we do this?
Well it depends on what takes your fancy that day…..but this is normally something you would do within some <script> tags on your web page.
Using the plain old JavaScript method
document.getElementById("username").focus()
In Dojo
dojo.byId("username").focus()
In jQuery
$("#username")[0].focus()
NOTE
We use the [0] to get the DOM Node element and use the HTML focus() method
.focus() when applied to a jQuery object is an event handler which determines what happens when you focus on something - be careful to use correctly
$('#target').focus(function() { alert('Handler for .focus() called.'); });
In HTML5
The autofocus attribute of a field is new in HTML5 (thanks to David Walsh). You can also focus on a button and other DOM objects
<input autofocus="autofocus" /> <button autofocus="autofocus">Hi!</button> <textarea autofocus="autofocus"></textarea>
