Reputation: 2712
I'm having an issue with jQuery on Rails 3.2.8. I've installed the jquery-rails gem and my application.js 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 an alert telling me that jQuery is indeed loaded.
However, no jQuery commands will work, even basic ones are unresponsive:
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});
I've tried everything -- even reincluding jQuery through the Google API. Any ideas on what might be going on?
Upvotes: 4
Views: 4956
Reputation: 9173
Although its too late for an answer but still i'll provide as i was having the same problem and wasted like 2 hours on it. Remove the comments in your js file as they are ruby comments and not js comments. If you remove them and write your js code, it'll work fine.
Upvotes: 0
Reputation: 8521
Make sure you're including the javascript include tag before the yield
in your application.html.erb
. If you're using Bootstrap, I think the default application.rb
loads JS after the yield, which makes it necessary to wait until jQuery is loaded before running it in your views.
If that's the case and you don't want to relocate the include tag higher 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.
}
}
Upvotes: 1
Reputation: 2712
Fixed it!
in application.html.erb, I changed the ordering of these two lines from:
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
to:
<%= javascript_include_tag "application" %>
<%= stylesheet_link_tag "application", :media => "all" %>
Now it works! I'm not quite sure why though, can anybody explain?
Upvotes: 2
Reputation: 3578
You probably want to check the console in the browser you are testing.
In jQuery's case, $ 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 have called jQuery.noConflict() somewhere, removing the alias?
http://api.jquery.com/jQuery.noConflict/
Upvotes: 1