How to use Javascript in Ruby on Rails?

14,921

Solution 1

Have you found this?
Where to Stick Your JavaScript.

Where to Stick Your JavaScript

Whether you use the Rails asset pipeline or add a <script> tag directly to a view, you have to make a choice about where to put any local JavaScript file.

We have a choice of three locations for a local JavaScript file:

  • the app/assets/javascripts folder
  • the lib/assets/javascripts folder
  • the vendor/assets/javascripts folder

Here are guidelines for selecting a location for your scripts:

  • Use app/assets/javascripts for JavaScript you create for your application.
  • Use lib/assets/javascripts for scripts that are shared by many applications (but use a gem if you can).
  • Use vendor/assets/javascripts for copies of jQuery plugins, etc., from other developers.

In the simplest case, when all your JavaScript files are in the app/assets/javascripts folder, there’s nothing more you need to do.

Add JavaScript files anywhere else and you will need to understand how to modify a manifest file.

Mysterious Manifests
There are two kinds of files in a JavaScript assets folder:

  • ordinary JavaScript files
  • manifest files
    You can also have CoffeeScript files and ERB files which are variations on ordinary JavaScript files.

Manifest files have the same .js file extension as ordinary JavaScript files. Manifest files and ordinary JavaScript files can be combined in a single file. This makes manifest files mysterious, or at least non-obvious.

The default app/assets/javascripts/application.js file is a manifest file. It’s a manifest file because it contains directives:

//= require jquery  
//= require jquery_ujs  
//= require_tree .

Directives tell Sprockets which files should be combined to build a single JavaScript script. Each file that contains manifest directives becomes a single JavaScript script with the same name as the original manifest file. Thus the app/assets/javascripts/application.js manifest file becomes the application.js script.

All scripts in the app/assets/javascripts folder are automatically added to the default application.js script when the manifest file includes the default //= require_tree . directive.

Hope this helps.

Solution 2

If you're using Rails 5 you may need to add jQuery to your project by adding

gem 'jquery-rails'

in your Gemfile, as well as adding

//= jquery

to your app > assets > javascript > application.js file.

Since Rails 5 uses Turbolinks, you may also need to change the listener

$(document).ready to $(document).on('turbolinks:load', function(main());

Adding a console.log to the main function will help with debugging to see if the event is being fired.

Share:
14,921

Related videos on Youtube

Martin
Author by

Martin

Updated on July 16, 2022

Comments

  • Martin
    Martin almost 2 years

    I think I'm fundamentally misunderstanding how to implement Javascript in my rails app. My understanding was that you throw your Javascript into your application.js file and then you can reference elements in your DOM using jQuery in order to make an interactive web page.

    I just checked through all of my code, and it looks clean (posted below in case I'm wrong). My thought is that I may be putting my Javascript in the wrong place, or I'm missing a dependency somewhere? I found other posts to be mostly unhelpful for me. How do I merge Javascript into my app?

    application.js

    function main() {
      $('.answers-box').hide();
      $('.qaa-box').on('click', function() {
        $(this).next().slideToggle(400);
      });
    }
    $(document).ready(main());
    

    page.html.erb

    <div class="qaa-box">
      <h4>Lorem ipsum dolor sit amet, consectetur adipiscing elit</h4>
      <p class="answers-box">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit
      </p>
    </div>
    
  • Martin
    Martin over 6 years
    Okay, so I have the gem. I added //= jquery to my application.js. I tried both $(document).ready and the other method and added a console.log No dice. Its not even firing. What should I do to troubleshoot this? How do I get rails to listen to this?
  • Martin
    Martin over 6 years
    This is super helpful, and I read through the article you posted, now I know, at least, where to stick my javascript, I'm still having trouble getting it to run though. :/
  • Andy
    Andy over 6 years
    In troubleshooting rails, you first want to check any spellings. Double check your functions, names, variables, etc. Then restart the rails server. If those don't work make a very simple jQuery function you know 100% will work, like $('.qaa-box').on('click', function() { console.log("jQuery fired") }); and place it inside of main. Use that to determine if jQuery is firing events or not
  • Martin
    Martin over 6 years
    I did that. It is not firing events. What do I do now?
  • Andy
    Andy over 6 years
    Try changing $(document).on('turbolinks:load ... to document.addEventListener("turbolinks:load", function() { alert("ok!") }); and see if that works
  • Martin
    Martin over 6 years
    this is on the right track. It made the alert "ok!" pop up. Now how should I write my callback to load my function? I tried playing with the above callback with my function and wasn't able to get it to work.
  • Andy
    Andy over 6 years
    Easiest way would be to remove the function and place it directly into the body: gist.github.com/anonymous/f02d9e4cf0038fc1420643255dedc64b