onokumus / metismenu

A collapsible jQuery menu plugin
https://onokumus.github.io/metismenu/
MIT License
1.96k stars 485 forks source link

Rails 5 Turbolinks JQuery workaround? #121

Open austinwalter opened 7 years ago

austinwalter commented 7 years ago

So before Rails 5 came out using metisMenu and Turbolinks wasn't a problem because the jquery.turbolinks gem fixed the discrepancies. But with Rails 5 that doesn't seem work anymore.

I was wondering if anyone knows of a work around?

sjnims commented 7 years ago

@austinwalter I was having the same issue you are describing. After some searching around, I saw the same strategy a few times. Per the turbolinks github readme, attaching event listeners to window.onload, DOMContentLoaded, or jQuery ready doesn't work with turbolinks because those events don't fire except for on page load and reload. Instead, turbolinks has it's own "DOM ready" event that fires after content is loaded, namely turbolinks:load. Here is the link to the section in the readme.

The suggestion I kept seeing (and is also in the turbolinks readme) is to use the following for javascript:

document.addEventListener("turbolinks:load", function() {
  // ...
})

For jQuery I used (and what is working for me in my project):

$(document).on('turbolinks:load', function() {
  // ...
});

Hope this helps!