Thoughts on life, liberty, and information technology

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!

2 responses to “Set initial input focus the easy (JavaScript) way”

  1. Robert Heinig Avatar
    Robert Heinig

    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…

    Like

  2. brian Avatar
    brian

    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);

    Like

Leave a reply to Robert Heinig Cancel reply