Set initial input focus the easy (JavaScript) way

I wanted a simple way to set the input focus on a web page. The use case I wanted was this:

<input ... class="focus" />

All I want to do is add the focus class to a form field. To get this to work, I whipped up a little JavaScript (using Prototype):

function setDefaultFocus()
{
	var focus = $$(".focus");
	if ( focus.length > 0 )
	{
		focus[0].focus();
	}
}
Event.observe(window, 'load', setDefaultFocus);

The result: After your page finishes loading, the first element found with the focus class will be given the focus. Done!

0 thoughts on “Set initial input focus the easy (JavaScript) way

  • Robert Heinig says:

    Now there must be an easy equivalent using the $get or $find or $object or whatever that come for free if you’re inside an asp.net2+ajax+toolkit project…

  • To do it in ASP.Net AJAX, you would need a method to get an element using CSS selectors, which is available in the ASP.Net Futures (July 2007). With that, you could do this;

    function setDefaultFocus()  
    {  
      var focus = Sys.UI.DomElement.selectElement('.focus');
      if ( focus != null ) focus.focus();  
    }
    Sys.UI.DomEvent.addHandler(window, 'load', setDefaultFocus);  

    In theory that should work. If you don’t want to wait for the selectElement() method to be implemented, you can set the ID of the object to receive the focus, and use the $get() method.

    function setDefaultFocus()  
    {  
      var focus = $get('focus');
      if ( focus != null ) focus.focus();  
    }
    Sys.UI.DomEvent.addHandler(window, 'load', setDefaultFocus);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.