Reputation: 1560
I'm building a Rails 3 app, and trying to get the jQuery .on() function working. It's currently not doing anything.
In assets/javascripts/v-application.js:
console.log('application');
$('body').on('click', function(){
alert('test');
});
When the app loads, the console displays "application" (as it should), but when I click on the body, no alerts fire. If I paste that exact same javascript into the console and click on the body, the appropriate alert fires.
If I view v-application.js in the browser, it shows the function.
I am using the latest versions of jquery-rails (2.0.1) and rails (3.2.2). This is all in the development environment.
What's going on that Rails doesn't know how to handle that basic function call? Does this have to do with the asset pipeline? How can I get that working?
Upvotes: 0
Views: 129
Reputation: 9167
Are you using jQuery 1.7.1? That's when .on came about, had the issue before.
jsFiddle here: http://jsfiddle.net/LmC6x/
As @loganfsmyth said though, I'd recommend using the ready function.
Upvotes: 0
Reputation: 161457
I'm going to guess that you don't have a ready function.
$(function() {
$('body').on('click', function(){
alert('test');
});
});
If you stick the code directly in the main JS file, doing $('body')
will not find anything, because when the script tag is interpreted, the body tag hasn't been processed yet. Sticking the logic inside a ready function will wait for the whole document to be parsed.
Upvotes: 2