JQuery does not work with Rails 3.2.8

I have a problem with jQuery on Rails 3.2.8. I installed gem jquery-rails and my application.js application has the following:

//= require jquery //= require jquery_ujs //= require_tree . 

views / layouts / application.html.erb has

 <%= javascript_include_tag "application" %> 

A simple Javascript test in test.js:

 if (jQuery) { alert('Jquery is loaded') } else { alert ('Jquery is not loaded') } 

gives me a warning telling me that jQuery is really loaded.

However, no jQuery commands will work, even the main ones do not respond:

 $(document).ready(function(){ $("a").click(function(event){ alert("Thanks for visiting!"); }); }); 

I tried everything - even re-enabling jQuery through the Google APIs. Any ideas on what might happen?

+4
source share
4 answers

Fixed!

in application.html.erb, I reordered these two lines:

 <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> 

in

 <%= javascript_include_tag "application" %> <%= stylesheet_link_tag "application", :media => "all" %> 

Now it works! I don’t quite understand why, can anyone explain?

+2
source

You probably want to check the console in the browser you are testing.

In the case of jQuery, $ is just an alias for jQuery, does the following work

 jQuery(document).ready(function(){ jQuery("a").click(function(event){ alert("Thanks for visiting!"); }); }); 

Perhaps you called jQuery.noConflict () somewhere, removing the alias?

http://api.jquery.com/jQuery.noConflict/

+1
source

Make sure you include the javascript include tag before yield in application.html.erb . If you use Bootstrap, I think by default application.rb loads JS after exiting, which makes it wait for jQuery to load before running it in your views.

If this is the case and you do not want to move the include tag above on the page, you can do this:

 runScript(); function runScript() { if( window.$ ) { // Make sure jquery is loaded // your jquery code here } else { window.setTimeout(runScript, 100); // If not, wait 100 milliseconds and try again. } } 
+1
source

Although it is too late for an answer, but still I will provide, because I had the same problem and wasted as 2 hours on it. Remove comments in the js file as they are ruby ​​comments, not js comments. If you delete them and write your js code, it will work fine.

0
source

Source: https://habr.com/ru/post/1443633/


All Articles