Monday, December 7, 2009

Automatically focus first input field using JQuery

jQuery is a well know JavaScript framework. It has core libraries which contains many useful out of the box functions, that makes JavaScript code writing much better, easier, cleaner and cross browser. On top of jQuery there are many ready to use widgets and components that can be integrated into your web application in relatively short time. jQuery core js can be downloaded from jQuery main site, but it is much easier calling Google CDN (content delivery network) for getting jQuery. For example, if you want to use jQuery version 1.3.2 you can simply request this link:

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

or, as a JavaScript tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Google has wide range of jQuery versions for your selection. It also offers additional frameworks and libraries as well (like MooTools, Yahoo UI and more). You can find more material about it in Google AJAX Libraries API.

Automatically focusing the first input field in web page that contains a form is a small but important feature in terms of user experience. Doing it in jQuery is an easy task:

<script type="text/javascript">
  $("input:text:visible:first").focus();
</script>

Of course, this code should be put after your form fields to function properly.

Note that the code is generic and doesn’t relate to any specific element id on the page.

No comments:

Post a Comment