I’m fairly new to coding in general, learning to code in rails, and feel like I’m missing something very fundamental with jquery.
On my user profile page, there’s a link for users to change their avatar picture:
<div id="show_avatars_choice">
<%= link_to "Change Avatar", "#", remote: true %>
</div>
Then, in /assets/javascripts/users.js, I have:
$("#show_avatars_choice").on("click", function(event){
event.preventDefault();
alert("you clicked me");
})
Ultimately the alert will be replaced with some code that allows a selection of alternative avatar pictures to be displayed, but at this stage even the simple alert doesn’t pop up when I click on the link. What am I doing wrong?
The application.js file does contain the following lines:
//= require jquery
//= require jquery_ujs
//= require_tree .
Thanks in advance for any responses.
What Tracy Fu said was correct, the element should be on the page before the bind. Her answer is correct, but it’s shorter if you do:
See it in action: http://jsfiddle.net/sXVzU/
Also did some changes to Tracy Fu’s fiddle: http://jsfiddle.net/4qRjt/