franksort
franksort

Reputation: 3143

Rails, JQuery: onClick event not attaching?

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?

Upvotes: 0

Views: 4967

Answers (2)

franksort
franksort

Reputation: 3143

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);

Upvotes: 2

Adil
Adil

Reputation: 148110

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");
      });
    });
    

Upvotes: 2

Related Questions