javascript on a partial - ruby on rails

1.3k views Asked by At

I have a partial that gets loaded every 3 seconds using AJAX (Prototype framework), this way:

  <script type="text/javascript">
   new Ajax.PeriodicalUpdater('content', '/shouts/update.js', { method: 'get', frequency: 1});
</script>

this is the part of the controller that loads the partial:

respond_to do |format|
    format.js {render(:partial => 'content', :locals => {:content => @last_shout.content})}
end

this is the content of the partial "_content.html.erb" :

<h2><%= content %></h2>

So far everything works great.

I want to add, that every time the partial will be reloaded, it will be fadeIn using Scriptaculous framework. I added this code to the _content.html.erb partial:

 <script type="text/javascript">
$('content').fade({ duration: 3.0, from: 0, to: 1 });
</script>

The problem was that instead of executing the code every time the partial gets reloaded, it executed it only one time. What do I need to do on order to make javascript code execute every time the partial gets loaded ?

2

There are 2 answers

0
giraff On

I would move the fading part into the AjaxUpdater:

<script type="text/javascript">
   new Ajax.PeriodicalUpdater('content', '/shouts/update.js', { method: 'get', frequency: 1, onComplete: function() {$('content').fade({ duration: 3.0, from: 0, to: 1 });}});
</script>

It could be a matter of timing (the text is replaced before onComplete is called, but the script within the text is evaluated earlier.)

0
andrea On

have a look at the rjs docs ... http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html

you could use it with jquery using jrails ...

then instead of

{render(:partial => 'content', :locals => {:content => @last_shout.content})}

you could accomplish the same action in the associated rjs files and add some other functions.

It's simple to use , look at some example online .