Rails 7 with Turbo & jQuery not working / only working at first page load

32 Views Asked by At

I am using Rails 7 with the default turbo installation. I also want to use Materialize CSS and jQuery. The jQuery $(document).ready... functions work on first page load but not ever after.

This is a problem that has been reported 100x but none of the solutions fix it for me.

Here is my application.js:

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"


$(document).ready(function(){
    $('.sidenav').sidenav();
    console.log('Turbolinks finished loading the page');
});

And my application header:

  <head>
    <title>Remind</title>
    <%= favicon_link_tag asset_path('favicon.ico') %>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">  
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
    
  </head>

This works fine the first time but since turbo is not reloading the head, it doesn't work afterwards. Note: The suggested solution of using document.addEventListener('turbolinks:load',... does not work AT ALL!

I am close to removing turbo from the app.

1

There are 1 best solutions below

0
Alex On BEST ANSWER

turbolinks is not turbo. This is very well documented:

document.addEventListener("turbo:load", function() {
  $('.sidenav').sidenav();
  console.log('Turbo finished loading the page');
})

https://turbo.hotwired.dev/handbook/building#installing-javascript-behavior