When you display a form, it’s always a nice practice to ensure that the first element of the form has focus as soon as the user can interact with the page. For example, if you went to Google’s homepage and had to click in the search box before you could start typing your question, it would bother you. But you don’t have to, you just zip over to Google and as soon as the page is loaded you can start typing.
It’s not the browser’s responsibility to set focus, it’s yours. The good news is that it’s really easy. All you need is a little bit of JavaScript code that looks a little something like this:
<script type="text/javascript"> first_element_of_form.focus(); </script> |
Of course the above pseudo-code assumes that you have already identified or hard coded (yikes!) the variable first_element_of_form. That’s not hard to do, but it will be a cumbersome solution if you expect the form to change because you’ll have to recode that little function every time the form changes.
A better solution (and still a very simple one) is to let jQuery do all the heavy lifting of identifying the first form element on the page so you don’t have to worry about future changes.
Here’s a simple, universal solution that will work for any page assuming you want focus on the very first input element:
<script type="text/javascript"> $(document).ready(function() { $(':input:first').focus(); }); </script> |
This uses jQuery’s amazing selector engine to identify the first input element on the page. Note: The first element is defined by the DOM, not the layout! Nevertheless, this function will identify the first element whether it is a textarea, text input, password field, checkbox, etc. and set the focus.
There are many alternatives to the above code. For example, the following selects the first text element:
<script type="text/javascript"> $(document).ready(function() { $(':text:first').focus(); }); </script> |
This segment selects the first text element within the form with id=”form2″:
<script type="text/javascript"> $(document).ready(function() { $('#form2 > :text:first').focus(); }); </script> |
I recommend getting familiar with jQuery’s selectors and reviewing the various filters that jQuery provides. In many cases, if you’re doing a lot of looping and searching for elements in the DOM directly in your code, you’re doing it wrong. Getting a handle on CSS will help you in your jQuery development, so learn CSS and print out a jQuery cheat sheet. You’ll be glad you did!
Comments:









{ 1 trackback }
Comments on this entry are closed.