Ask A Question


You’re not receiving notifications from this thread.

CoffeeScript - How to work with coffeescript in ruby on rails?

theshashiverma asked in Javascript

I am working with CoffeeScript in Ruby on rails. And I am using to convert my javascript and jquery into CoffeeScript.

We know, Ruby on Rails provides us by default .coffee files when we create any controller.

In my view folder, I have defined a test.html.erb file, I have a button

<button id="p">try</button>
and if I define the script for this button by using javascript or jquery in the same page i.e. test.html.erb it works.

My javascript code

document.getElementById("p").onclick = function() {myFunction()};
function myFunction() {

and my jquery


And now I have created a custom file in app/assets/javascripts/

coffeescript of my jquery code

$(document).ready ->
  $('#p').click ->
    alert 'hello'

and when I use this in my it works fine.

coffeescript of javascript code

myFunction = ->
  alert 'hello'
document.getElementById('p').onclick = ->

and when I use this code in my it shows error in my console

Uncaught TypeError: Cannot set property 'onclick' of null
I have also try the but still get the same error

so should I only use the coffeescript generated by jquery or is there any way to use the coffeescript generated by javascript?


One important note to make:

Rails 6 will be using Webpacker by default for Javascript, so it will probably be getting rid of coffeescript as well. You might want to just make the upgrade now if you can so you'll have an easier time upgrading to Rails 6.

Your error is saying the variable you called ".onclick" on was null. The variable was the result of your getElementById, so it's saying it can't find that element on the page. I'd check that out.

Your Coffeescript looks fine, so I'd double check your HTML and make sure it has something with id="p" in it.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,603+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.