How to focus on a form input text field on page load using jQuery?
Bind the focus to the #inputID when the document is fully loaded. Just replace #inputID with the ID of your input element. Remember to load jQuery first, or else this just will not work!
Breaking down how jQuery focus works
Simple enough, right? But what if you feel adventurous and want to dive a little deeper? Let's break this down to granular level!
Targeting different types of inputs
Not every input field always has an ID, sometimes we want to focus on the first visible input field:
This little tip just might save you a headache or two!
Wrestling with dynamic content
When dealing with dynamically loaded content, we need to make sure the DOM is all dressed up and ready to go:
Dynamic content can be a wild beast; luckily, we got jQuery on our side!
HTML5 autofocus
: a hero or a false friend?
HTML5 introduced autofocus
attribute, and it seemed like a silver bullet:
Well, this is awkward... Internet Explorer is afraid of the autofocus
! To help this ol’ guy out, we should provide a jQuery fallback:
Remember, good web developers leave no browsers behind(cough except IE6 perhaps).
Respecting HTML5, mobile users and accessibility
Auto-focusing input fields on mobile devices can bother users by popping up keyboard UI. Not to mention the accessibility implications:
This is for those evenings when you promise to code "just a little bit" and end up fixing accessibility at 3 AM.
Why not pure JavaScript?
Missing jQuery? Use vanilla JavaScript for a guilt-free, zero-calorie alternative:
Sometimes, pure JavaScript is all you need - no sugar, no gluten, all taste!
UX and Usability: Don’t steal the spotlight!
Use auto-focusing sparingly. Too much can annoy users and lead to a frustrating experience. Remember, with great power (to focus) comes great responsibility.
Dynamic Focus: Adapt to the User
Sometimes, it is better to lead the focus based on the user's actions:
Was this article helpful?