简体   繁体   中英

Ruby on Rails DOM updates only work after page reload

I'm updating a class name for the html element depending on the current route. I also have some jquery to display a menu when an element is clicked. When I'm on the home page the html class is correctly added to the html element and the menu is correctly displayed when clicked. However, when I navigate to another route by clicking the nav link the route changes correctly but the html class name is not updated and the jquery doesn't fire anymore.

application_helper.rb

  def html_class(class_name)
    content_for(:html_class) { class_name }
  end 

application.html.erb

<html class="<%= yield(:html_class) || '' %>"> <!-- class is only updated on page reload -->

home.html.erb

<% html_class 'nail' %>

projects/index.html.erb

<!-- no html_class provided, should default to '' -->
<div class="row projects">
  <% @projects.each do |project| %>
    <%= render project %>
  <% end %>
</div>

site.js

// when route changes page must reload to fire

$(function() {
  $('#initials').click(function() {
    $('.slider, .nav-btn').toggleClass('closed');
  })
});

Try wrapping your jQuery with the below. The issue is likely caused by Turbolinks which loads pages that you click on with AJAX to speed it up. So this wrapper tells the Javascript to fire on the turbolinks load instead of on a full page refresh.

$(document).on('turbolinks:load', function() {
  $('#initials').click(function() {
    $('.slider, .nav-btn').toggleClass('closed');
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM