Explain Codes LogoExplain Codes Logo

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

html
responsive-design
accessibility
best-practices
Nikita BarsukovbyNikita Barsukov·Oct 27, 2024
TLDR

Setup immediate focus on a text box upon page load using HTML5's autofocus attribute:

<input type="text" autofocus> <!-- Fast and furious, no JavaScript needed! -->

This simple setup positions the cursor in the selected text input field – all it takes, is pure HTML.

Understanding the magic spell: autofocus

The autofocus attribute in HTML5 is as efficient as it gets. On one hand, it is supported by a range of modern browsers and, on the other, its implementation is super easy. You can use the autofocus in three ways – autofocus, autofocus="" or autofocus="autofocus" – pick your favorite!

<input type="text" autofocus> <!-- Straight to the point, no beating around the bush! -->

No more waiting: Instant action

Unlike its JavaScript-based siblings such as the onload event handlers, the autofocus attribute is an immediate attention grabber. It reduces redundancy, squashes complexity, and brings user focus right where you want it. What’s more? It is also perfectly suited for non-JS environments.

Accessibility: Making the web for everyone

Weaving in autofocus into accessible web forms ensures a smooth user experience regardless of the navigational tools they use. It's like rolling out the red carpet, directing users straight to the key action point.

Facing the ghosts: Browser support and fallbacks

While autofocus has solid support in modern environments, it might feel ghosted in some older browsers. Haunted by this possibility? Fear not, consider potential fallbacks such as CSS tricks to visually emphasize the input field. Keep in mind though, these do not place the cursor.

Design decisions: Autofocus in action

When designing web interactions, strategic placement of the autofocus can create smooth user journeys. Be it the search box of a knowledge base or the username field of a sign-up form – it's all about making the user feel at home.