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
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/
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.
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?
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.
}
}