JavaScript
Article

Set Focus on First Field with jQuery

By Sam Deering

This is how you “Set Focus on First Field with jQuery!”

This is a simple snippet of code that sets focus with the mouse cursor in the first field of a form on a webpage as soon as it is loaded. It works in Internet Explorer, Firefox and Safari browsers.

You may think this code works but it doesn’t set the cursor in the input box:
$(‘#input’).focus();

Instead use this code this will work properly:

//set focus to first input box
        $('#input').focus();
	$("#input:text:visible:first").focus();

input-first-field-jquery

See Live Demo

Event Handler
This is how you can add an event handler to catch when a user clicks the input field.

$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Useful HTML

< !DOCTYPE html>


  
  


  

focus fire

focus fire

  • http://bitcomplex.se Bobo

    I absolutely hate it when web sites do this.

    The problem, that I want to see addressed, is that if you, as a visitor to a site, has started to interact with it before it’s completely loaded the site SHOULD NOT change focus!

    Numerous times I’ve found myself typing my password in plain text in the username field when the site I’m visiting uses this technique to put focus on the first login field. #fail

  • jquery4u

    @bobo – I agree with you on that one! Maybe developers should add a few lines of code that checks if certain fields are empty before assigning the focus of a field.

  • http://www.antistandard.com/ James

    sorry I can’t see it work in your demo or on my site

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.