javascript - Rails 5: Trying to render divs with a single partial but keep the div class unique so that JQuery doesn't fire on all partials -
a bit of confusing title.
i trying implement bit of reddit comment system. can view post , add comment polymorphic. or, comment on comment.
my view looks so:
<h2>post:</h2> <div class="well"> <p> <strong>title:</strong> <%= @post.title %> </p> <% if @post.description %> <p> <strong>description:</strong> <%= @post.description %> </p> <% end %> </div> <% if current_user %> <%= render "shared/comment_form" %> <% else %> <p>log in add comments</p> <% end %> <% if @post.comments.any? %> <%= render "shared/comment_list" %> # comment_form inside of partial <% else %> <p>no comments yet</p> <% end %> inside of comment_list rendering of comment_form can comment on comment:
<h2>comments</h2> <ul> <% @post.comments.each |co| %> <li><%= co.body %></li> <%= render "shared/comment_form" if current_user %> <% end %> </ul> finally, comment form itself:
<div id="comment-form" class="form-group"> <%= form_for @comment, remote: true, url: post_comments_path(@post) |f| %> <%= f.text_area :body, required: true, rows: 5, class: "form-control" %> <%= f.hidden_field :commentable_id, :value => @post.id %> <%= f.hidden_field :commentable_type, :value => @post.class.name %> <%= f.hidden_field :user_id, :value => current_user.id %> <br> <%= f.submit class: "btn btn-primary" %> <% end %> </div> <span id="add-comment">add comment</span> and jquery code acts on comment_form:
$(document).on('turbolinks:load', function() { $("#comment-form").hide(); $('#add-comment').click( function() { $("#comment-form").fadetoggle("fast"); ($("#add-comment").text() === "cancel") ? $("#add-comment").text("add comment") : $("#add-comment").text("hide"); }); }); my question is:
how separate these divs jquery doesn't fire on instances of id="comment-form? pass in erb tag <%= @post.class.name %><%= @post.id %>, again, keep variable universal. then, how implement unique id name in jquery code.
edit: got 1 part of question solved. left rest of wasn't able see.
you use prev() this:
$(document).ready(function() { $('.comment-form').hide(); $('.add-comment').click( function(event) { // store button has been clicked on variable var eventtarget = $(event.target); // find previous element #comment-form , id , toggle eventtarget.prev('.comment-form').fadetoggle('fast'); // use eventtarget again (eventtarget.text() === 'cancel') ? eventtarget.text('add comment') : eventtarget.text('cancel'); }); }); you can see in action here: http://codepen.io/rebagliatte/pen/mbknjv
Comments
Post a Comment