I’ve got the following index.js.erb:
$(function () {
var $team = $('#createTeam'),
$user = $('#createUser'),
$userPanel = $('.createUserPanel'),
$teamPanel = $('.createTeamPanel');
$user.click(function(){
$userPanel.append('<%= j render 'form_user' %>').fadeIn('slow');
$(this).fadeOut();
});
$team.click(function(){
$teamPanel.append('<%= j render 'form_team' %>').fadeIn('slow');
$(this).fadeOut();
});
})();
To go along with these links in my index.html.erb:
<%= link_to "+", "#", 'data-action' =>"create",'data-target'=> "team", id: "createTeam", remote: true %>
<%= link_to "+", "#", 'data-action' =>"create",'data-target'=> "user", id: "createUser", remote: true %>
When I click on either of the links the first time, nothing happens, but on the successive 2nd and 3rd clicks both forms appears. After each click of the link the button should fade out and the form should appear in a separate div.
The desired implementation is when either link is clicked the form_* will appear, and the button will fade out. How do I achieve this?
The problem is that you’re calling javascript that’s then loaded and binding events to your elements. That’s why the 2nd click works — the click event is bound after the first click which “calls” the javascript to come be loaded.
It looks like you don’t need anything dynamic from your AJAX call. You can remove the “remote: true” option from the link_to helper and simply place the contents of index.js.erb in your index.html.erb (probably at the bottom or in the :script content block)
I usually don’t end up using the remote helper stuff, but, think of it like an AJAX call, you want to make a request to an action, have it processed, and return some kind of information about what happened