How do I create an preview field for auto_html?
My controller:
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
def preview
post = Post.new(params[:comment])
render :text => post.body_html
end
My view:
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :titel %><br />
<%= f.text_field :titel %>
</div>
<div class="field">
<%= f.label :body_html %><br />
<%= f.text_area :body_html %>
</div>
<div class="field">
<%= f.label :up_votes %><br />
<%= f.text_field :up_votes %>
</div>
<div class="field">
<%= f.label :down_votes %><br />
<%= f.text_field :down_votes %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<div id="post-preview" style="width:400px;border:1px solid black; height:500px;"></div>
I want to make an preview of the title and the body_html.
Example the a user types “Hello helloe helloe” in the body_html text_area it would instant gets previewed in a div below.
There was an example of this feature here: http://rors.org/2010/08/15/auto_html.html
But it does not work anymore.
To do it on the client-side, just use an onfocus on the textbox element which will create an event listener. This function will set another event listener which will activate on keydown and activate another function. This final function will run whenever the user types something, and will access the contents of the textbox and put it into the preview div.
Sending it off to the server is amazingly inefficient, unless you’re doing syntax highliting, in which case you could send it off every 10 seconds or so.
P.S. By the way, if you want to do the auto_html stuff, you can occasionally send it off to the server to do that.