Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't focus with jQuery?

I’m trying to focus on input when the search icon is clicked so the user can start typing without having to click on the input manually. Ideally, it should be something like this, but focus() doesn’t work on this input for some reason.

$('.header__icons a[role="button"]').click(function(){
     $('#q').focus();
})

I’ve tried various options, but nothing..I see this input gets "focus-visible" and "data-focus-visible-added" when clicked on. I tried adding them manually, but it doesn’t focus it either. I also couldn’t locate any functions related to this in the files.

EDIT: The code works fine, just added setTimeout..and dev console was the reason I wasn’t seeing any changes here 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Actually, the code you have should work. I recommend you close the browser’s developer console and test it again.
The reason it probably doesn’t work is that focus() doesn’t steal focus from the dev console.

Try using a setTimeout in the dev console and then quickly click in your browser window, then you should see it focus the search box.

setTimeout(function() { $('input[name="q"]').focus() }, 3000);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading