I'am having trouble by loading a Javascript file (which includes jQuery) in Ruby on Rails.
$(document).ready(main);
var contador = 1;
function main(){
$('.menu_bar').click(function(){
if(contador == 1){
$('nav').animate({
left: '0'
});
contador = 0;
} else {
contador = 1;
$('nav').animate({
left: '-100%'
});
}
});
};
The proper html.erb looks like this:
<header>
<div class="menu_bar">
<a href="#" class="bt-menu"><span class="fa fa-bars"></span>Brand</a>
</div>
<nav>
<ul>
<li><%= link_to "Link 1", '#'%></li>
<li><%= link_to "Link 2", '#'%></li>
<li><%= link_to "Link 3", '#'%></li>
</ul>
</nav>
</header>
The proper application.js includes:
//= require rails-ujs
//= require turbolinks
//= require jquery
//= require jquery_ujs
//= require_tree .
jquery is sourced in the Gemfile with gem 'jquery-rails'.
The animation is not loading after clicking. I am using Rails 5 and I guess the problem is issued by Turbolinks.
What do I have to change to solve this problem?
Turbolinks tries to follow every link (even if it's a #
, in which case it just reloads the page). You have a few ways around this.
Option 1: Change your link to not have any href:
<div class="menu_bar">
<a class="bt-menu"><span class="fa fa-bars"></span>Brand</a>
</div>
Option 2: Stop the event from propagating, so that it doesn't reach turbolinks:
$('.menu_bar a').click(function(e) {
e.preventDefault();
console.log("I HAVE BEEN CLICKED");
// Rest of code here...
return false;
});
Option 3: "Tell" turbolinks not to follow #
links:
$(document).on('turbolinks:click', function (event) {
if (event.target.getAttribute('href').charAt(0) === '#') {
return event.preventDefault();
}
});
If it doesn't work, add a few console.log
within the code to find out which part it's not getting to. There might be some issues with the CSS (which is not shared so we can't help there), but it might require a relative or absolute position to move the nav
.
Hopefully this sets you in the right direction, let me know if it doesn't work and what have you found out after debugging, and I'll update my answer.