1

running Rails 6.0.3.3 and can't get jQuery to work.

Here's packs/application.js

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

And in my view I have something like this:

<head>
<%= javascript_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 
</head>

 <div id="pop">
   TEST
 </div>
 <script>
    $(document).ready(function() { 
        $('#pop').hide(); 
      });
 </script>

And so when my page loads I would expect the #pop div that says 'TEST' to NOT show. It seems as if this set up is just not working. Thoughts?

Wes Creations
  • 337
  • 2
  • 10

1 Answers1

1

Rails 6 doesn't include JQuery by default. It looks like you didn't install it.

Here's a link that shows how does Webpack works and how to install JQuery with Rails 6.

But if just want to install JQuery, here is how to do it:

Run yarn add jquery in your project.

Be sure to check if Jquery has been successfully installed by checking your package.json and yarn.json where the JQuery package should be visible.

Then add this snippet in your environment.js:

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

Your environment.js should then look like this:

const { environment } = require("@rails/webpacker");
const webpack = require("webpack");

environment.plugins.append(
  "Provide",
  new webpack.ProvidePlugin({
    $: "jquery/src/jquery",
    jQuery: "jquery/src/jquery",
  })
);

module.exports = environment;

Now simply add require('jquery') in your application.js.

application.js file:

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

b0rdjack
  • 35
  • 5
  • THank you. Trying this now. Running into an issue, where is this environment.js file you speak of? – Wes Creations Oct 03 '20 at 23:02
  • THank you. Trying this now. I was able to paste that code into the environment.js and the application.js files, but it still isn't working :( any other thoughts? – Wes Creations Oct 03 '20 at 23:10
  • Did you install jquery by running `yarn add jquery` ? Also do check in the console of the developement tools if you get any error message. – b0rdjack Oct 04 '20 at 11:53
  • @WesCreations Did you get jQuery working? And where is the environment.js file? I'm trying to get it to work myself: https://stackoverflow.com/questions/75178270/how-do-i-add-jquery-to-mastodon-4-02-using-rails-6-and-webpacker-4 – BlueDogRanch Jan 28 '23 at 15:41