Skip to content

Commit f4c69fb

Browse files
Ensure components are initiated when a page uses Turbo
1 parent f5822c8 commit f4c69fb

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

app/assets/javascripts/application.js

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import "@hotwired/turbo-rails";
22
import {
33
createAll,
4+
isSupported,
45
Button,
56
Checkboxes,
67
ErrorSummary,
@@ -15,8 +16,7 @@ import { UpgradedRadios as Radios } from "./components/radios.js";
1516
// Configure Turbo
1617
Turbo.session.drive = false;
1718

18-
// Initiate NHS.UK frontend components on page load
19-
document.addEventListener("DOMContentLoaded", () => {
19+
function initializeComponents() {
2020
createAll(Autocomplete);
2121
createAll(Button, { preventDoubleClick: true });
2222
createAll(Checkboxes);
@@ -25,4 +25,30 @@ document.addEventListener("DOMContentLoaded", () => {
2525
createAll(Radios);
2626
createAll(NotificationBanner);
2727
createAll(SkipLink);
28+
}
29+
30+
// Initiate components once page has loaded
31+
document.addEventListener("DOMContentLoaded", () => {
32+
initializeComponents();
33+
});
34+
35+
// Reinitialize components when Turbo loads (and preloads) a page
36+
document.addEventListener("turbo:load", (event) => {
37+
// Skip if initial page load (already handled by DOMContentLoaded)
38+
if (event.detail?.timing?.visitStart) {
39+
if (!isSupported()) {
40+
document.body.classList.add("nhsuk-frontend-supported");
41+
}
42+
43+
initializeComponents();
44+
}
45+
});
46+
47+
// Reinitialize components when Turbo morphs a page
48+
document.addEventListener("turbo:morph", () => {
49+
if (!isSupported()) {
50+
document.body.classList.add("nhsuk-frontend-supported");
51+
}
52+
53+
initializeComponents();
2854
});

0 commit comments

Comments
 (0)