Explain Codes LogoExplain Codes Logo

Is it autofocus="autofocus" or autofocus?

html
best-practices
responsive-design
accessibility
Alex KataevbyAlex Kataev·Feb 24, 2025
TLDR

In HTML, autofocus is employed to set an element into focus upon page load. Both versions—autofocus="autofocus" and simply autofocus—are correct. While both work, using autofocus is tidier and generally recommended.

<input type="text" autofocus>

This ensures that the text input will be the primary focal point when the page loads.

Quick dive into boolean attributes

For autofocus and other similar boolean attributes, HTML5 considers them as true for their mere existence. The longer form, autofocus="autofocus", can be used for clarity, but it's not a requirement. Remember the HTML mantra: "Less is more."

Compatibility: XHTML vs HTML5

Your choice to use autofocus or autofocus="autofocus" may depend on your specific use case or target demographic. For strict XHTML fans, the longer form is preferable, but HTML5 is easygoing. To cover all your bases, go with autofocus that has wide support and saves your bytes.

Code cleanliness

When it comes to HTML, cleanliness is key—not just for you, but also for other developers who may read your code. A well-structured code with the autofocus attribute (with no unnecessary whitespaces) is easier to read and less prone to potential mix-ups.

Dispel the misconceptions

Here's a common myth: autofocus="false" or autofocus="0" has effect. However, in the reality of HTML5, it's a big no-no. The rule is that if a boolean attribute like autofocus appears, it's tantamount to a thumbs up (true).

A note on accessibility

While autofocus can be a neat trick, bear in mind its impact on accessibility. For users relying heavily on keyboard navigation, an unexpected autofocus might feel like an unwanted auto-scroll. Use sparingly and remember—user experience matters.

Browser compatibility: Best practices

To minimize any legacy issues or cross-browser inconsistencies, stay clear of using autofocus="". Stick to autofocus or autofocus="autofocus" to ensure the highest level of compatibility and predictability across all devices and browsers.