JavaScript does not execute when navigating from page to page

I am creating my first Ruby on Rails application and I tried to create an animated navigation bar. I use jQuery and turbolink.

This is mine application.js(under /app/assets/javascripts)

$(document).ready(function(){
  $("#nav").hover(function(){
    $("#nav").animate({left:'10px'});
  },
  function(){
    $("#nav").animate({left:'-220px'});
  });
});

And in application.html.erb(under app/views/layouts) I have

<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

and my super navigation bar, which now looks like this (also in application / views / layouts)

<div id='nav'>
  <%= image_tag('arrow.png', size: '20x20', id: "arrow") %>
  <ul>
    <li><%= link_to 'Main page', root_path%></li>
    <li><%= link_to 'Résumé', resume_path %></li>
  </ul>
</div>

When I download my application, the animation works, but when I go to another page of the application, the animation stops working. If I click F5, it works again

So, if I want to use my navigation bar, I need to refresh every page.

Do you know what I can do to fix this?

+2
1

, , Rails Turbolinks.

Rails 4.0 Turbolinks, -. Turbolinks , . , Turbolinks . Turbolinks , JavaScript , , . , Turbolinks, turbolinks Gemfile.

JavaScript. , , Rails Turbolinks, JavaScript:

// accommodate Turbolinks
$(document).on('ready page:change', function() {
. . .
})

Turbolinks page:change, . page:change JavaScript. , Turbolinks (, ).

, Learn Ruby on Rails, JavaScript Turbolinks.

+3

Source: https://habr.com/ru/post/1548225/


All Articles