Becky Bolton Becky Bolton - 3 months ago 21
CSS Question

jQuery drop down menu not toggling on page reload

I have a responsive dropdown menu animated through jQuery in my Rails app, but it's getting stuck on the open position when I follow one of the menu links. I can keep following links, but the menu remains open.

In my application.html.erb:

<header>
<button class="hamburger">&#9776;</button>
</header>

<div class="menu">
<ul>
<% if current_user %>
<li><%= image_tag @user.profile_picture.thumb.url, class: 'profile_thumb' %> <span><%= current_user.email %></span></li>
<% end %>
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Pledges", pledges_path %></li>
<% if current_user %>
<li><%= link_to "Edit Profile", edit_user_registration_path %></li>
<li><%= link_to "Log out", destroy_user_session_path, method: :delete %></li>
<% else %>
<li><%= link_to "Sign In", new_user_session_path %></li>
<li><%= link_to "Register", new_user_registration_path %></li>
<% end %>
</ul>
</div>


My jQuery in application.js:

$(document).ready(function() {

$('.menu').hide();

$('.hamburger').on('click', function() {
$('.menu').slideToggle('slow');
});

});


It's located in app/assets/javascripts, linked in the head of application.html.erb as such:

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>


Thanks for your time.

Answer

By the sounds of it, it is a turbolinks issue. Depending on your version of rails wrap it in the following instead.

var ready = function() {

  $('.menu').hide();

  $('.hamburger').on('click', function() {
    $('.menu').slideToggle('slow'); 
  });

};

$(document).on('ready', ready);
// Rails 5 || Turbolinks 5
$(document).on('turbolinks:load', ready);
// Rails 4 || Turbolinks < 5
$(document).on('page:load', ready);
Comments