Debugging JavaScript focus() issues

Have you ever had a complex bit of JavaScript setting focus on elements after inputs for accessibility that didn’t quite work? This little line may help, I know it saved my bacon.

While implementing some accessibility fixes to a complex website I had one instance of jQuery $(‘.inputs input:first-child’).focus() which wasn’t returning focus. It would instead put focus onto something which was hidden. Using the line below I was able to watch the console as the page was interacted with.

setInterval(function(){ console.log(document.activeElement); }, 500);

It prints the currently active element to the console. This will work best in Chrome and Firefox, but you could easily modify it (eg, print to the page) for any other browser.

It revealed that part of the selector was clashing with something else which was easy to fix. I hope this helps you to.

Leave a Comment