Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery not working in rails

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.

like image 833
Ester Lin Avatar asked Oct 27 '15 23:10

Ester Lin


1 Answers

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.

like image 194
Richard Peck Avatar answered Sep 27 '22 23:09

Richard Peck