0

In my Rails 6 project, I have been trying to use the asset pipeline to get application.js to use jQuery and a JavaScript file at app/assets/javascript/event_index.js, but neither are working. I am getting an Uncaught ReferenceError: $ is not defined when I load my web page, and my JavaScript code is not doing anything when I click on things.

Things I have tried:

  • The top answer to this StackOverflow question suggests that I can just write //=require events_index to get events_index.js, but this isn't doing anything
  • I didn't realize that my //= require lines have to be in the header. When I changed that, it still didn't help
  • I ran gem 'jquery-rails'
  • I was using $(document).ready() previously, but apparently because Rails 6 uses TurboLinks, this doesn't work anymore, so I changed it

Here is the full text of my application.js file:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require events_index

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

$( document ).on('turbolinks:load', function() {
    console.log( "ready!" );
});

Thanks for your help!

  • [This article](https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker) ended up being helpful for me – Caleb Biddulph Aug 01 '20 at 17:45

1 Answers1

0

Rails 6 comes with webpacker by default, you should instead install jquery via yarn and load it via webpacker. See How to add jquery third party plugin in rails 6 webpacker

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70
Samy Kacimi
  • 1,216
  • 9
  • 23