Question

I am adding nested (reddit-like) comments to my app; so far I'm just using comment divs, where in my CSS I do this:

.comment {
  margin-left: 40px;
}

This works fine for displaying comments. My question is what is the cleanest way to now add reply forms to each comment (and only show it when the user clicks a reply button of some sort)?

Is this usually done by adding all the input boxes for the comments right away, hiding them at first, and then only showing them if the user clicks on a reply button? Or perhaps should I only append the relevant <form> HTML code to a given div once the user clicks reply for that comment?

What is the cleanest way to do this?

Was it helpful?

Solution

You can do that by having one form field hidden somewhere in the html and when ever user clicks on the commect clone the form element and append it to the comment div

checkout this jsFiddle example below is the code snippet

<div class="comment">
    comment1
</div>
<div class="comment">
    comment2
</div>
<div style="display:none">
    <form id="commentForm">
        <textarea name="comment"></textarea>
    </form>
</div>

var Comment = {
    init: function() {
        $(".comment").bind('click', $.proxy(this.handleClick, this));
    },
    handleClick: function(evt) {
         var form = $('#commentForm').clone();
         var target = $(evt.target);
         var isFormAvailable = $("#commentForm", target).length > 0;
         if(!isFormAvailable) {
             $(evt.target).append(form);
         }
    }   
};

$(function() {
    Comment.init();
});

OTHER TIPS

Keep a template of the form somewhere in your document and keep it hidden. On click of reply next to any comment, do following.

  1. Clone the template (you can jquery clone function)
  2. Set a hidden field in the template to the id of the comment for which reply is been clicked
  3. append it next to comment that need to be replied

I'll go with this.

Keep the input boxes with each comment right away doesn't make sense. It's unnecessarily increasing the size of the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top