Search code examples
javascriptvue.jsfocusaccessibilitysingle-page-application

Reset focus on Vue SPA page


I'm developping Vue SPA with Vue router app and I'm trying to simulate oage reload, by resetting focus state after changing the route. Here is my code:

router.beforeEach((to, from, next) => {
  document.activeElement.blur();
  next();
});

My problem is that focus indeed returns to body element right after change, but on next focus it goes back to where it was, in this case footer, instead of "skip to content" button. I tried setting focus to window explicitly, but it doesn't work either. Does anyone have an idea how to reset focus flow for real, so it truly starts over? Any help will be appreciated!


Solution

  • Basing on this article I added tabindex -1 right before and removed it right after. It did the trick

    router.beforeEach((to, from, next) => {
      document.body.setAttribute("tabindex", "-1");
      document.body.focus();
      document.body.removeAttribute("tabindex");
      next();
    });