0

I am new to jQuery and I want to apply a fade in effect to an item being created in my rails application. The object appends to the DOM but the fade effect doesn't seem to work! This seems like it should be a fairly easy solution but I think the rails instance variable is throwing things off. I have tried wrapping my create javascript in a document ready function but that didn't seem to help either. Thank you in advance!

index.html.erb

<div class="row">
  <div class="col-lg-12">
    <% @events.each do |event| %>      
      <%= render event %>
    <% end %>
  </div>
</div>

create.js.erb

$('#new_event').remove();
$('#new_event_link').show();
$('#events').append('<%= j render(@event) %>').fadeIn(5000);

_events.html.erb

<ul id="events">
  <li>
    <h4><%= event.location %></h4>
    <p><%= event.description %></p>
  </li>
</ul>

For others, below is the working code

index.html.erb

<div class="row">
  <div class="col-lg-12">
    <ul class="events">
      <% @events.each do |event| %>      
        <%= render event %>
      <% end %>
    </ul>
  </div>
</div>

create.js.erb

$('#new_event').remove();
$('#new_event_link').show();
$('#events').append($('<%= j render(@event) %>').hide().fadeIn(5000));

_events.html.erb

<li>
  <h4><%= event.location %></h4>
  <p><%= event.description %></p>
</li>
pyRabbit
  • 803
  • 1
  • 9
  • 33

1 Answers1

2

The fade in effect doesn't show because once you append the new elements they are already visible, so there is nothing to fade in. The correct way to do this is described in this answer. I made a quick fiddle with the general idea.

By the way, I don't quite understand your templates, I think they should look like:

index.html.erb

<div class="row">
  <div class="col-lg-12">
    <ul id="events">
      <% @events.each do |event| %>      
        <%= render event %>
      <% end %>
    </ul>
  </div>
</div>

_event.html.erb

<li>
  <h4><%= event.location %></h4>
  <p><%= event.description %></p>
</li>
Community
  • 1
  • 1
Jakub K
  • 1,713
  • 1
  • 13
  • 21
  • Thank you for your feedback, I made the suggestions that you provided but it didn't work for me this time. For the record, I was following the Railscast Episode #136 when making this. I think the render(@event) portion is screwing all this up because the jQuery is pretty straight forward like you described. – pyRabbit Apr 19 '14 at 23:54
  • Nevermind! Not sure what I did wrong the first time but it works now with your suggestion! Thanks ! – pyRabbit Apr 20 '14 at 00:25