Reputation: 2202
I am trying to write my first js code in my new Rails5 app and cannot seem to get Jquery to work, guessing it's a config/environment issue but despite all my searching and confirg alterations I cannot seem to get it running. Can anyone see what it is that I'm doing wrong?:
gemfile;
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
application.html.erb;
<title>MyEngine</title>
<!-- Gon::Base.render_data -->
<%= Gon::Base.render_data %>
<%= csrf_meta_tags %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
new.html.erb;
<%= link_to 'Remove Employee', '#', id: 'hide-employee' %>
quotes.coffee;
$(document).on "page:change", ->
$('#hide-employee').click ->
alert "Clicked!"
And no alert when clicked. No errors, server running and page rendering fine, just nothing in console.
Thanks for the help.
Upvotes: 3
Views: 3275
Reputation: 9943
For those coming here because they have Rails 5.1, jQuery is no longer a default dependency. From the release notes:
jQuery was required by default in earlier versions of Rails to provide features like data-remote, data-confirm and other parts of Rails' Unobtrusive JavaScript offerings. It is no longer required, as the UJS has been rewritten to use plain, vanilla JavaScript. This code now ships inside of Action View as rails-ujs.
You can still use jQuery if needed, but it is no longer required by default.
To add it back in, add to the Gemfile
:
gem 'jquery-rails' # Use jquery as the JavaScript library
and then
$ bundle
Upvotes: 2
Reputation: 113
Make sure you're app/assets/javascripts/application.js contains:
//= require jquery
//= require jquery-ujs
Note: If you're using Rails 5.1 you can omit //= require jquery_ujs
in favor of //= require rails-ujs
.
Also, consider removing turbolinks entierly. Doing so has resolved more asset pipeline issue than I care to count. I have a feeling it's not providing you much value anyway. :-)
Remove turbolinks with:
$ bundle
.//= require turbolinks
from app/assets/javascripts/application.js"data-turbolinks-track" => true
hashes from app/views/layouts/application.html.erb.Upvotes: 0
Reputation: 2222
Try using turbolinks:load instead.
$(document).on 'turbolinks:load', ->
$('#hide-employee').click ->
alert 'Clicked!'
Upvotes: 3
Reputation: 42044
The page:change event is defined in turbolinks-classic. This version is now deprecated like you can see by yourself.
Instead, you can use turbolinks:load or turbolinks:render or turbolinks:before-render.
Upvotes: 1