0

I think I'm missing out on some fundamental aspect of how Javascript is handled by Rails.

I created a new Rails project using Ruby 2.1.0.

$ mkdir whatishappening
$ cd whatishappening
$ rails new .
$ rails generate scaffold post title body:text
$ rails db:migrate
$ rails server

I then proceeded to create a test post. After that I added:

whatishappening/app/views/posts/show.html.erb

<a href="#" id="foo">link</a>

whatishappening/app/assets/javascripts/posts.js (I renamed this from posts.js.coffee)

console.log("posts.js loaded");

$("#foo").on("click", function(event) {
  console.log("link clicked");
});

When I run via rails server and monitor the Javascript console in Chrome, I see:

> posts.js loaded

However, I don't see

> link clicked

when I click the link.

Can someone explain what's happening?

2 Answers 2

2

You can check two things.

  • You added jQuery successfully, you can find how to added jQuery here.

  • Your binding code executes when foo is added to DOM, you can use document.ready to ensure that.

    console.log("posts.js loaded");
    
    $(document).ready(function(){
     $("#foo").on("click", function(event) {
        console.log("link clicked");
      });
    });
    
Sign up to request clarification or add additional context in comments.

2 Comments

you need $(document).on('page:load', ready) if you use turbo-links
if you use turbo-links you need not only @Monk_Code's code (useful tip sure) but also you need to read this article staal.io/blog/2013/01/18/dangers-of-turbolinks
2

Using the answer from @Adil and the tip from @Monk_Code, I found the following the be the best solution considering that the default Rails 4 install includes Turbolinks.

app/assets/javascripts/posts.js

console.log("posts.js loaded");

var ready;
ready = function() {

  $("#foo").on("click", function(event) {
    console.log("link clicked");
  });

};

$(document).ready(ready);
$(document).on("page:load", ready);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.