Panel widget script won't run after navigating away and back to dashboard

I have a custom panel widget that needs to run some javascript/jquery in order to upload a file while staying on the same page. It works just fine when I login to the panel then upload a file. But when I navigate to anywhere in the panel then come back to the dashboard, the script won’t run again until I reload the browser. I have the script wrapped in $(document).ready(function() {... in the widgits/widget-name/template.php file, but that doesn’t seem to help after panel navigation.

How do you trigger the script? Is there an upload button with an event handler?

The issue here is that the JavaScript is only executed once after you loaded the panel. After then Kirby 2 does not make “hard” requests anymore and just loads the view via JSON which contains a string of html.

Depending on your knowledge and browser setup I’ld suggest to make use of a mutation observer.

Using this API you can listen to added or removed DOM nodes, attribute changes and fire a callback to reinitiate your JS.

By the way I faced a similar issue in my kirby-analytics-dashboard Plugin. I found a quite hacky way :see_no_evil:

1 Like

@texnixe that’s exactly right.

Edit: sorry the picture text is so small. Basically the form submits to my dummy url ("?") if the JS hasn’t been attached and run preventDefault() on the form.

@gearsdigital this makes total sense. I had no idea the Kirby 2 panel was an SPA. With the mutation observer, would I just look for the existence of a unique div#id that only appears in my widget on the Dashboard? Then re-attach the event handler if that div#id is present?

That is what I’ld do :slight_smile: A made a quick fiddle for you…

1 Like

Thanks so much @gearsdigital. I used the fiddle, added a flag to prevent multiple firings (because for some reason the mutation observer fired multiple times), and it works a beauty!

1 Like