Default the cursor inside the search field

My users are requesting that when they goto my search page, that the cursor already be blinking in the keyword field. Currently you have to click in there with your mouse. Is there an easy way to do this with PHP or even HTML?


You can use javascript to bring focus to the search field once the document(page) has been loaded.

I don’t really know javascript. Think there would be a snip of code out on the web that I could just copy and paste?

Are you using a JavaScript library at all?

I had a javascript that I was using for a form validator, but I ripped it out. So my site doesn’t use javascript at all right now.

Here’s a pretty interesting SO conversation on this. :slight_smile:

At the end of the body, just before the </body> tag, you can use this script.

Keep in mind that this depends on the value of your form identifier, and the name of the search field. In this example, the form has an id of “search” and the search field is called “q”

<form id="search">
    <input type="text" name="q">

var form = document.getElementById('search');

Hi Paul,

Would’nt you need to ensure the document was fully loaded first?

Scripts can access anything that appears before them in the DOM.
The standard location to speed up your web pages is to put your scripts at the end of the body, just before the </body> tag. Coincidentally that also means that the whole DOM is available to those scripts as well, which is why putting your scripts at the end of the body has become such a very useful technique.

    <script src="script.js"></script>

Ahhh I see, thanks for that.

I wasn’t sure how that would work because technically, the body element isn’t closed and it would be the root node of any element you would be targeting.

I’m sure you can tell I’m a JS noob. :slight_smile: