htmlformsthreaded-comments

Cleanest way to add reply forms to nested comments


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?


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();
    });