Skip to content

Instantly share code, notes, and snippets.

@cuibonobo
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save cuibonobo/11271254 to your computer and use it in GitHub Desktop.

Select an option

Save cuibonobo/11271254 to your computer and use it in GitHub Desktop.
Blog post about how I can only get focus to work if the page throws an error.

I'm trying to apply focus to the element that had it last after a page load, like this:

lastFocus.container.focus();

where lastFocus is the jQuery element that had been focused on last before the page load.

When I first load the page, the user hasn't focused on anything, so I just set lastFocus to document.activeElement. It should be focusable, but the console throws Uncaught TypeError: Cannot call method 'focus' of undefined.

The strange thing is that even if I change the code so that it doesn't run on the initial load, the first time it tries to focus will always throw the error. Plus, the code always works after the error is thrown at least once. In fact, if I put the code inside a try...catch, the fields never achieve focus properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment