Why is jQuery not working in my 5 rails app?

I'm trying to write my first js code in my new Rails5 app and can't seem to get Jquery to work, guessing it as a config / environment issue, but despite all my search and config changes, I can't seem to get it to work ... Can anyone understand what I am 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 warning appears when clicked. There are no errors, no server activity and no page rendering, just nothing in the console.

Thanks for the help.

+3


source to share


4 answers


Try using turbolinks: download instead.



$(document).on 'turbolinks:load', ->
  $('#hide-employee').click ->
    alert 'Clicked!'

      

+2


source


Event : Change is defined in turbolinks-classic . This version is now deprecated, as you can see for yourself.



You can use turbolinks: load or turbolinks: render or turbolinks: before-render instead .

+1


source


For those who come here because they have Rails 5.1, jQuery is no longer a default dependency . From the release notes :

jQuery was required by default in early versions of Rails to provide features like data-remote, data-confirm, and other parts of Rails' unobtrusive JavaScript offerings. This is no longer required as UJS has been rewritten to use plain, vanilla JavaScript. This code is now sent inside Action View as rails-ujs.

You can still use jQuery if needed, but by default it is no longer required.

To add it back add in Gemfile

:

gem 'jquery-rails'             # Use jquery as the JavaScript library

      

and then

$ bundle

      

+1


source


Make sure your app / assets / javascripts / application.js contains:

//= require jquery
//= require jquery-ujs

      

Note. If you are using Rails 5.1 you can omit //= require jquery_ujs

in favor //= require rails-ujs

.

Also, consider removing the turbo pumps. This resolved more pipeline problems than I would expect. I feel like it doesn't give you much value. :-)

Remove turbo pumps with

  • Remove turbo science from Gemfile and $ bundle

    .
  • Remove //= require turbolinks

    from app /assets/javascripts/application.js
  • Remove both hashes "data-turbolinks-track" => true

    from the app /views/layouts/application.html.erb.
0


source







All Articles