I am currently working on a comments feed feature. By default, only the first four comments are displayed, with an option to show more when clicking the "show more" anchor. The issue I'm facing is that if new comments are dynamically added, the CSS hides the comment in the fourth position, disrupting the flow of the feed. What I want is for any newly added comment to replace the one at the bottom if it's shown before clicking the anchor, and if the anchor has been clicked previously, the newest comment should be displayed on top while hiding the current last comment that was visible. The code snippet below demonstrates this functionality.
var _divNum = jQuery('div.commentsWrapper > div').length;
if (_divNum > 4) {
$('.showMoreAnchorWrapper').fadeIn(300);
}
jQuery(document).on('click', '#showMoreAnchor', function() {
jQuery('div.commentsWrapper > div:hidden').slice(0, 4).slideDown(300);
if (jQuery('div.commentsWrapper > div').length === jQuery('div.commentsWrapper > div:visible').length) {
jQuery('#showMoreAnchor').fadeOut(300);
}
});
jQuery(document).on('click', "#postButton", function(e) {
var textAreaContent = jQuery("#textAreaInput").val().trim();
var html = "<div class='commentAreaWrapper'><div class='titleStyle'><span class='imgWrapper'><img class='' style='min-width:48px; min-height:48px; clip:rect(0px, 48px, 48px, 0px); max-width:48px' src='' alt='Admin'></span>Admin</div><div class='commentArea'>" + textAreaContent + "</div></div>";
jQuery(html).prependTo(".commentsWrapper").hide().slideDown();;
var _divNum = jQuery('div.commentsWrapper > div').length;
if (_divNum > 4) {
jQuery('.showMoreAnchorWrapper').fadeIn(300);
}
});
.globalWrapper {
height: 50%;
width: 50%;
margin-bottom: 15px;
margin-left: 10px;
}
/* CSS styles go here */
.showMoreAnchorWrapper {
text-align: center;
margin-top: 10px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
/* HTML content goes here */