I'm using jQuery in a Rails app to create a dropdown menu. At first I thought it was a sprockets issue. The code in my nav.html.erb file is:
<nav>
<%= link_to '#', class: 'toggle' do %>
<i class="fa fa-bars"></i>
<span>Menu</span>
<% end %>
<ul class = "menu-items">
<li>
<%= link_to root_path do %>
<span>Home</span>
<% end %>
</li>
<li>
<%= link_to about_path do %>
<span>About</span>
<% end %>
</li>
<li>
<%= link_to projects_path do %>
<span>Projects</span>
<% end %>
</li>
<li>
<%= link_to blogs_path do %>
<span>Blog</span>
<% end %>
</li>
<li>
<%= link_to contact_path do %>
<span>Contact</span>
<% end %>
</li>
</ul>
</nav>
The code in my nav.js file is:
$(document).ready(function() {
var $switch = $('a.toggle'),
$menu = $('nav ul.menu-items'),
$icon = $('nav a.toggle i');
$switch.on('click', function(e){
e.preventDefault();
$menu.toggle(function(){
$icon.toggleClass('fa-bars fa-times');
});
});
});
When I refresh the page, I press menu nav bar and it reveals the drop down menu. I can click on one of the menu items and will be redirected to the page. On the new page I click the menu bar again and I get it's default behaviour, which just adds '#' to the url.
I think it has something to do with the document.ready function. On page refresh, the document.ready function runs but doesn't after being redirected from a page when I click a menu item.