JSFiddle - React, Tailwind, and code Playground
by john_s
HTML
<div class="user_id">USERID</div>
<div class="feeds">
<div class="post" data-id="7"><!-- Put the post ID on the post element -->
<h5>Post Header</h5>
<p>post 123</p>
<div class="comments">
<div class="comment_container"><!-- Always include this, even if empty -->
<div class="comment"><p>Comment 2013-12-15</p></div>
<div class="comment"><p>Comment 2013-12-14</p></div>
</div>
<button type="button" class="show_more_comments">Show more</button>
<div class="new_comment">
<textarea class="comment_text" rows="1" autocomplete="off" placeholder="Have your say..."></textarea>
<button type="button" class="add_comment">Add Comment</button>
</div>
</div>
</div>
</div>
JavaScript
$('.add_comment').click(function() {
var $post = $(this).closest('.post'),
post_id = $post.attr('data-id'),
comment_text = $post.find('.comment_text').val(),
user_id = $('.user_id').text();
$.ajax({
url: '/echo/html/',
type: 'POST',
data: { html: 'done', delay: 1 },
dataType: 'text'
}).done(function(msg) {
$post.find('.comment_text').val('');
$.ajax({
url: '/echo/html/',
type: 'POST',
// For the real site, you will want to pass the following.
// data: { user: user_id, post: post_id, index: 0, max: 1 }
// On the server side, you will use "LIMIT index, max", and since
// you pass index=0 & max=1, only the most recent comment will be
// returned.
data: {
html: '<div class="comment"><p>' + comment_text + '</p></div>',
delay: 1
},
dataType: 'html'
}).done(function(msg) {
$post.find('.comment_container').prepend(msg);
});
});
});
$('.show_more_comments').click(function() {
var $post = $(this).closest('.post'),
post_id = $post.attr('data-id'),
user_id = $('.user_id').text(),
comment_count = $post.find('.comment_container').children('.comment').length;
// NOTE: comment_count tells how many comments are currently being displayed.
$.ajax({
url: '/echo/html/',
// This ajax call could be to the same URL as the second ajax call for the
// add button.
type: 'POST',
// For the real site, you will want to pass the following.
// data: { user: user_id, post: post_id, index: comment_count, max: 3 }
// On the server side, you will use "LIMIT index, max", and since
// you pass index=comment_count & max=3, up to three comments will be returned,
// starting after the ones already being displayed.
...