Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dcranmer's avatar

global event for setting focus on inertia route change (SOLVED)

Using Laravel, Inertia, and Vue 3. I want to set the focus to the h1 on every route change. Is there a way to set a global event listener on, for example, Inertia's start event in app.js? I've tried suggestions from LaryAI, but so far nothing is working. Can I do this globally (assuming I add tabindex="-1" to all h1s), or does this need to be done in setup on every Vue "page" component?

0 likes
4 replies
LaryAI's avatar
Level 58

To set the focus on the h1 element on every route change using Laravel, Inertia, and Vue 3, you can create a global event listener in your app.js file.

First, you need to listen for the start event in Inertia. This event is fired before the page transition begins. You can use the Inertia.on method to listen for this event.

Inside the event listener, you can use the document.querySelector method to select the h1 element and then call the focus method on it to set the focus.

Here's an example of how you can implement this solution in your app.js file:

import { Inertia } from '@inertiajs/inertia';

Inertia.on('start', () => {
    const h1Element = document.querySelector('h1');
    if (h1Element) {
        h1Element.focus();
    }
});

Make sure to import the Inertia object from @inertiajs/inertia at the top of your app.js file.

With this solution, the focus will be set on the h1 element on every route change. You don't need to add the tabindex="-1" attribute to all h1 elements unless you have specific accessibility requirements.

Note: If you're using Vue 2 instead of Vue 3, you can still use this solution. Just make sure to import the Inertia object from @inertiajs/inertia-vue2 instead.

dcranmer's avatar

Would anyone else be good enough to address this, please? If a global listener for an inertia start event is not possible, maybe setting awatcher or watchEffect on the current route? There's got to be a way to do this globally.

Niush's avatar
Niush
Best Answer
Level 50

Using Inertia's on navigate event.

// app.js / layout.vue

import { router } from '@inertiajs/vue3';

router.on('navigate', () => {
  const el = document.querySelector('h1.page-header');

  if (el) {
    el.focus();
  }
});
<h1 class="page-header focus:bg-red-100" tabindex="-1">
	Hello
</h1>
1 like
dcranmer's avatar

@niush Yes, this works! (I had the wrong event -- I'd been searching for the right one all morning, then tried watching for a props change, etc.). Thank you! And unfortunately, I also let LaryAI send me on a wild goose-chase. Sometimes it's great, and sometime not so much. Thanks again!

Please or to participate in this conversation.