Focus Your Forms with Prototype Events
July 11th, 2006
It has been rather quiet around here as I have been rather busy lately trying to get the next release of the GiftHat.com out the door.
In the meantime, here is a simple technique I like to use to focus a form on a web page using Prototype’s built in Events:
The solution
For those of you who just want to dive right in, here is the solution:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script src="/javascripts/prototype.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
Event.observe(window, 'load', function() {$('focus').focus()}, false);
//]]>
</script>
<form action="/login" method="post" name="loginForm">
<label for="username">Username</label><br/>
<input id="focus" name="user[username]" size="30" tabindex="1" type="text" />
<label for="username">Username</label><br/>
<input name="user[password]" size="30" tabindex="1" type="password" />
<input name="commit" tabindex="3" type="submit" value="Submit" />
</form>
</body>
</html>
The explaination
This line requires the prototype library:
<script src="/javascripts/prototype.js" type="text/javascript"></script>
The Event.observe javascript is where the magic happens:
<script type="text/javascript">
//<![CDATA[
Event.observe(window, 'load', function() {$('focus').focus()}, false);
//]]>
</script>
This will setup an event that will cause our dynamic function to be called when the window loads. This function will lookup an element that has an ID called focus and call its focus() method.
In case you are wondering what the CDATA part is for, that will just make sure this webpage still validates.
The last part of this is to create an element that has an ID of focus which will get the browser focus after the window loads. In the example above, it is this form element that gets the focus:
<input id="focus" name="user[username]" size="30" tabindex="1" type="text" />
You can definitely do a lot more interesting things with Prototype events than this example, but this should help get the ball rolling.
Subscribe to the feed!
Leave a Reply