shashi verma
shashi verma

Reputation: 973

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

I am working with CoffeeScript in Ruby on rails. And I am using http://js2.coffee/ 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() {
    alert("hello");
}

and my jquery

$(document).ready(function(){
    $("#p").click(function(){
        alert("hello");
    });
});

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

coffeescript of my jquery code

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

and when I use this in my test.coffee it works fine.

coffeescript of javascript code

myFunction = ->
  alert 'hello'
  return

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

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

Uncaught TypeError: Cannot set property 'onclick' of null

I have also try the test.js.coffee 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?

Upvotes: 0

Views: 1776

Answers (3)

Varinder Sohal
Varinder Sohal

Reputation: 1292

We can add java-script using back-tick(`) in coffee-scripts.

window.onload = ->
   `document.getElementById("demo").onclick = function() {myFunction()};

   function myFunction() {
       document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
   }`

Upvotes: 0

killernova
killernova

Reputation: 160

Your first method is called after document ready, but your last one is called earlier than the first one in which time the element with id of 'p' may haven't created yet, so document.getElementById('p') return null, and raise the error above.

Upvotes: 1

Talha Junaid
Talha Junaid

Reputation: 944

The problem is element_with_id "p" is not found on the page because coffeescript is being load before the page load. Wrap your code inside document.ready this will call the coffeescript once the page is completed loaded.

$(document).ready ->
  myFunction = ->
   alert 'hello'
   return

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

Upvotes: 4

Related Questions