Explain Codes LogoExplain Codes Logo

Focus Input Box On Load

html
responsive-design
focus-engineering
accessibility
Nikita BarsukovbyNikita Barsukov·Nov 26, 2024
TLDR

Focus on an input box instantly using autofocus:

<input type="text" autofocus>

Alternatively, invoke .focus() with JavaScript once the page loads:

window.onload = () => document.getElementById('myInput').focus();

Ensure you've assigned id="myInput" to your specific input:

<input type="text" id="myInput">

Hey there, devs! Splendid user experience often starts from leading your users right to the action. Let's adventure into the craft of focusing an input box right after the page loads.

Digging deeper

Checking support for autofocus

Although HTML5 brings us autofocus, sometimes the quirkiness of browsers can be a party pooper. Employing feature detection helps in dealing with these cases:

if ('autofocus' in document.createElement('input')) { console.log('Autofocus is in the house'); } else { // When HTML5 decides to play hide-and-seek window.onload = () => document.getElementById('fallbackInput').focus(); }

Don't forget to assign an id to your trusty fallback input:

<input type="text" id="fallbackInput">

Cursor gymnastics

Need to summon your cursor at the end of the existing text in an input box? Say hello to setSelectionRange:

// It's like calling your cursor home for dinner const input = document.getElementById('myInput'); input.focus(); input.setSelectionRange(input.value.length, input.value.length);

Not ready to part with the initial text upon focus? Try this:

// It's like saying, "You can take a look, but you can't touch!" input.addEventListener('focus', function() { this.value = this.value; });

Scrolling in the deep

For text areas that would put War and Peace to shame, use scrollTop property to start from the bottom:

// Drake would be proud textarea.scrollTop = textarea.scrollHeight;

Taking care of cross-browser behavior

While every browser prides in its individuality, invoke window.onload to make sure the spotlight is on the input the moment everything loads:

// All eyes here please! window.onload = () => document.getElementById('universalInput').focus();

Polyfills for a smoother ride

Sometimes, browsers pretend to ignore autofocus and other newfangled HTML5 features. At such times, a polyfill steps in as your knight in shining armor:

// Polyfill to the rescue for browsers with commitment issues if (!('autofocus' in document.createElement('input'))) { // Your polyfill code comes here to save the day... }

Let's not forget about accessibility

A well-rounded solution respects tab order and keeps keyboard navigation alive and kicking – particularly crucial for users who use assistive technologies.

Special pointers

Focus within forms

Need a specific interaction model within a form? Managing the focus order becomes slightly trickier:

// Like an orderly queue at a cookie booth document.querySelector('form').addEventListener('submit', (e) => { e.preventDefault(); const inputs = Array.from(document.querySelectorAll('form input[type="text"]')); const nextInputIndex = inputs.indexOf(e.target) + 1; if (inputs[nextInputIndex]) { inputs[nextInputIndex].focus(); } });

Loading content dynamically

For dynamic content or Single Page Applications (SPAs), use a MutationObserver or framework-specific life-cycle methods to pull the focus:

// Like keeping an out for your friend in a crowd const observer = new MutationObserver((mutations, obs) => { const input = document.getElementById('dynamicInput'); if (input) { input.focus(); obs.disconnect(); // Stop looking once you find your friend } }); observer.observe(document, { childList: true, subtree: true });

Modals and focus

While dealing with modals, remember to trap the focus within to avoid any user experience mix-ups:

// Like keeping a lively puppy within a fenced yard function trapFocus(element) { const focusableEls = element.querySelectorAll('a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select'); const firstFocusableEl = focusableEls[0]; const lastFocusableEl = focusableEls[focusableEls.length - 1]; element.addEventListener('keydown', function(e) { if (e.key === 'Tab' || e.keyCode === 9) { if (e.shiftKey) { if (document.activeElement === firstFocusableEl) { lastFocusableEl.focus(); e.preventDefault(); } } else { if (document.activeElement === lastFocusableEl) { firstFocusableEl.focus(); e.preventDefault(); } } } }); }