8

I've read many pages about using jquery in rails and still can't seem to get it to work.

I have the 'jquery-rails' gem, and I installed. I have the require statements in the application.js file.

Here is a test page I keep running:

<!DOCTYPE html>
 <html>
 <head>
<title><%= yield(:title)%></title>
<%= javascript_include_tag 'application','jquery', 'data-turbolinks-track' => true  %>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<script>$(document).ready(function(){
  $(".bg-info").click(function(){
    $(this).hide();
});
 });</script>
</head>
<body>
<center>
<h1 class="bg-info"><%= yield(:title)%></h1>
</center>
</body>
</html>

But when I click on the "bg-info" text in the browser I get no response.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Ester Lin
  • 607
  • 1
  • 6
  • 20
  • this is a stretch but in your `assets/javascripts/application.js`, do you have the following line: `//= require jquery` . Or maybe `bundle install`? – philip yoo Oct 27 '15 at 23:22
  • Can you try the following: `<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>`. Remove `jquery` from that line, restart server, and try running – philip yoo Oct 27 '15 at 23:33
  • Try running `rake assets:clobber`. Maybe there are some asset cache problems – yivo Oct 27 '15 at 23:34
  • Open developer console in your browser and try to execute $(".bg-info").length (on that page where bg-info is located) – Src Oct 27 '15 at 23:39
  • Can you include your `application.js` file? – Graham S. Oct 28 '15 at 03:17

1 Answers1

6

Here's what you should have:

#app/assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require_tree .

$(document).on("click", ".bg-info", function(e){
   $(this).hide();
});

Here's what I'd do for the layout (to test):

#app/views/layouts/application.html.erb
<!DOCTYPE html>
 <html>
   <head>
       <title><%= yield(:title)%></title>
       <%= javascript_include_tag 'application','jquery', 'data-turbolinks-track' => true  %>
       <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
       <%= csrf_meta_tags %>
   </head>
   <body>
       <div class="bg-info"><%= yield(:title)%></div>
   </body>
</html>

If the above doesn't work out the box, you'll probably have an issue with your development environment (OS) -- most likely with ExecJS.

To confirm this, you'll need to debug your developer's console:

enter image description here

To access the dev console, right-click > inspect element > console.

This shows you any errors with your JS & your front-end environment. If any errors appear, they may tell you what the issue is.

If no errors appear, you should try installing NodeJS on your system, as this ensures Rails can use the appropriate JS executable.

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147