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?
$('.menu_bar').on('click', function() { ...
instead of$('.menu_bar').click(function(){ ...
. Are you getting any errors in the console?$('nav').css('position', 'relative');
in themain()
. (you can also try to share more info, like the HTML, JS and CSS)$('nav').css('position', 'relative');
but it doesn't work. The html.erb is edited in the description. The CSS is working fine: jsfiddle.net/wy6fxoaj.console.log('abc')
in your main function and see if it's called correctly, if not working at that time, Try$(document).ready(main); $(document).on('turbolinks:load', main);
to your javascript file