Focus on Input with JQuery

This is very simple and can also be done with HTML5 ‘autofocus‘ which I would recommend you use (if you can). If for some reason you need to control it with JavaScript, utalising jQuery’s .focus() event handler will get you out of trouble.

To focus on an input field with an id of search on page load, try:


$(document).ready(function() {
 $('#search').focus();
});

Jake Bresnehan

A Front End Developer based in Sydney and the creator of Web Design Weekly.

Web Design Weekly keeps developers at the forefront of techniques and trends whilst helping them learn and grow to produce top quality code to make the web a better place for all.

2 Comments

  1. Ive used this before to help support users who dont have a browser that supports the html5 autofocus, but this as autofocus should be used in circumstances that dictate its use. autofocussing on a form half way down a page can be a hinderance rather than a good feature.

    • Couldn’t agree more!

This post currently has 2 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

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

Current day month ye@r *