I am designing a search engine and I want to design it in a way that when user comes to the website the cursor should be already on the search bar. Right now the user needs to hit a tab or manually initiate cursor into the search bar. Any ideas how I can do that?

Dani AI

Generated

A couple of simple, reliable ways to put the cursor in the search box on page load.

The easiest and most future-proof option is the HTML5 autofocus attribute on the input itself. It requires no JavaScript and works across modern desktop browsers:

<input id="search" name="q" type="search" autofocus />

For pages that are generated dynamically, for Single Page Apps, or for older browsers that don’t respect autofocus, add a small client-side fallback that runs after the DOM is ready. Make sure the element is present and visible before calling focus to avoid no-ops or errors:

document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById('search');
  if (el && typeof el.focus === 'function') {
    try { el.focus(); } catch (e) {}
  }
});

A few troubleshooting and accessibility notes that build on ’s server-side suggestion and ’s confirmation that a focus fix worked here: mobile browsers often ignore autofocus to prevent the keyboard from popping up; focus won’t work while an element is hidden (inside a closed modal or display:none); back/forward cache can preserve focus—use the pageshow event for those cases; and auto-focusing can confuse screen-reader users, so consider whether autofocus is appropriate for your audience. For details about the HTML attribute and the focus API, see the MDN docs for input autofocus and HTMLElement.focus(). For accessibility guidance on autofocus, see WebAIM’s form controls notes.

in a page load event, write YourTextbox.Focus() in !isNotPostback code block.

[This is for Asp.Net C#, please see other syntax for VB.Net]

To implement it in JavaScript please see following example:

Thanks! It worked..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.