0

Context

I have a Rails 3 app I'm working on and have the 'jquery-rails' gem installed and

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

in my app/assets/javascripts/application.js file.

Alerts and coffeescript work ok IF they are base level items.

I've put them into app/assets/javascripts/application.js directly, app/assets/javascripts/pages.js and tried it as a coffeescript version in app/assets/javascripts/pages.js.coffee (just changed the file name)

As soon as I put them in something like:

$(document).ready(function(){
alert('works');
});

or (for coffeescript)

jQuery ->
  alert "hi"

It will not fire at all.

I've also tried including the jquery file in the application layout but same problems.

Question

Is there a different syntax for declaring jQuery functions within rails? Does anyone have any ideas what could be going wrong?

Any help is appreciated. Thanks!

Community
  • 1
  • 1
BJ McDuck
  • 164
  • 1
  • 12
  • 1
    Where did you put your js code? – xdazz Jul 31 '12 at 01:58
  • I'm not that used to looking for java errors in the browser. It says "Modernizr is not defined" and it links to Foundation.js:32 I'm using the Foundation framework from zurb. – BJ McDuck Jul 31 '12 at 15:15
  • Just added modernizr manually to my javascripts and now the error has gone, still testing to see if it resolved the issue. – BJ McDuck Jul 31 '12 at 15:27
  • Wow. That was all it was. That was driving me crazy. Adding modernizr seems to have solved the issue. Thanks Speransky. – BJ McDuck Jul 31 '12 at 15:29
  • You should take a look at this post: http://stackoverflow.com/questions/21219484/rails-4-jquery-ready-not-firing – Fernando Rybka Feb 15 '14 at 13:55
  • You should take a look at this post http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links – Fernando Rybka Feb 15 '14 at 13:57

4 Answers4

3

You spelled function wrong:

// $(document).ready(funtion(){
$(document).ready(function(){
    alert('works');
});
Josh Mein
  • 28,107
  • 15
  • 76
  • 87
0

I think coffee script does not work because it should be in file with appropriate extension.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

I needed to check the console log as Speransky mentioned, it was calling for modernizr because I had added the Foundation 3 framework manually. It couldn't get modernizr and so was somehow killing my jQuery powers.

I downloaded modernizr.js to app/assets/javascripts, I then added it before the tree:

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

That did it.

BJ McDuck
  • 164
  • 1
  • 12
0

Another common mistake: change .coffee to .js and forget to remove the top comments.

Fernando
  • 7,785
  • 6
  • 49
  • 81