New to using jQuery in Rails and can’t get a div to be recognized for click or hover event. Using coffeescript as well, but compile looks fine. The divs all look good in the elements window in Chrome dev tools, but I don’t get my console.log in the console window.
portion of my _form.html.haml
.field
= f.label :question
= f.text_field :question
%p Click the plus sign to add answers.
.field#answerone
= f.label :answers
= f.text_field :answers
#plusanswer
= image_tag("plusWhite.png", :alt => "plus sign")
.actions
= f.submit 'Save'
coffeescript:
$("#plusanswer").click ->
console.log("here we are")
$("#answerone").clone().appendto()
compiled javascript:
(function() {
$("#plusanswer").click(function() {
console.log("here we are");
return $("#answerone").clone().appendto();
});
}).call(this);
Is the way I’m doing the image_tag messing things up?
I believe Sergio is correct in his comment. If your JS comes before the page’s markup, then the selector
$(#plusanswer')runs before that element exists. You can verify this with the codeTo fix this, wrap your code in jQuery’s document ready wrapper, like so:
This looks a bit magical, but here’s how it works: When you pass a function to the jQuery object,
$, it runs that function only after thedocument‘s “ready” event fires. So, again assuming that your code precedes your markup, you should get this behavior: