I have a javascript file that looks like this:
// javascript/packs/org_chart.js
require("orgchart") // from jquery-orgchart plugin
document.addEventListener("turbolinks:load", () => {
console.log('org chart loaded')
$('#org_chart').orgchart({
...
});
})
and an org_chart.html.erb page that looks like this:
<div id="org_chart"></div>
<%= javascript_pack_tag 'org_chart', 'data-turbolinks-track': 'reload' %>
When I navigate to the org_chart route I expect the script to run but I get a blank page and blank console.
I can see that the script was included but it does not run.
When I navigate away from the page the script appears to run, but because the element is no longer on the page, I get an error. I continue to get this same error in the console every time I navigate until I refresh the page.
If I navigate back the script runs and the org chart loads correctly. The org chart also loads correctly if I do a refresh after navigating to the page.
When I navigate back and forth between any page and the org_chart page, the script runs again and the org chart duplicates itself each time.
How can I:
- Get the script to run when I navigate to the org_chart page.
- Get the script to not run when I leave the org_chart page (I thought that was what the
javascript_pack_tagwas supposed to do) - Stop duplication from happening each time I visit the page.


