Currently, I have a button called ‘Comment’ that when clicked slides down a comment box. I want the comment box to hide whenever the user clicks on any area of the page other than the comment box itself.
Currently, with my code the button just disappears when it is clicked. Could anyone point me in the right direction? Thanks!
Ruby ERB:
<% @entry.each do |e| %>
<div class="entry">
<p><%= e.entry %></p>
<small>Posted by <%= e.author %> at <%= e.created_at.strftime("%I:%M%p %m/%d/%Y") %></small>
<% if e.comments.nil? %>
<p>No Comments</p>
<% else %>
<% e.comments.each do |c| %>
<div class="comment">
<blockquote><strong><%= c.author %></strong> writes:<%= c.comment %></blockquote>
</div>
<% end %>
<% end %>
<div class="comments">
<a href="#" data-comment="<%= e.id %>" class="newcommentbutton">Comment</a>
<div class="newcomment" id="comment<%= e.id %>">
<%= form_for @comment, :url => entry_comments_path(e, @comment) do |f| %>
<ol>
<li><%= f.label :author %>
<%= f.text_field :author %></li>
<li><%= f.label :comment %>
<%= f.text_area :comment %></li>
<%= f.submit %>
</ol>
<% end %>
</div>
</div>
</div>
<hr />
<% end %>
<%= button_to "Write A Message", new_entry_path, :method => :get %>
Javascript:
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function()
{
$('.newcommentbutton').click(function()
{
var button = $(this);
var comment = button.attr('data-comment');
button.hide();
$('#comment' + comment).slideDown('fast', function() {
$('#comment' + comment + ' input[type=text]').focus();
});
});
$('.newcomment').click(function(event)
{
event.stopPropagation();
});
$('body').click(function()
{
$('.newcomment').hide();
});
});
Your new comment buttons also needs to stop propagation, like this:
You have the right idea, just remember that
.newcommentbuttonis also in<body>so it’s opening the comment form, then the click bubbles up and closes it.