Conceal HTML elements from the bottom as new content is being added dynamically

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 */

Answer №1

Try using this updated JS code and give it a test run. Hopefully, it meets your requirements 😊

var _divCount = jQuery('div.commentsWrapper > div').length;
if (_divCount > 4) {
    $('.showMoreAnchorWrapper').fadeIn(300);
}

jQuery(document).on('click', '#showMoreAnchor', function() {
    $($("#showMoreAnchor").parents(".globalWrapper")[0]).children(".commentsWrapper").attr("track", true);
    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 textContent = jQuery("#textAreaInput").val().trim();
    var htmlCode = "<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'>" + textContent + "</div></div>";

    jQuery(htmlCode).prependTo(".commentsWrapper").hide().slideDown();;
    if ($($("#showMoreAnchor").parents(".globalWrapper")[0]).children(".commentsWrapper").attr("track")) {
        var visibleBlocks = jQuery('div.commentsWrapper > div:visible');
        var lastBlock = visibleBlocks[visibleBlocks.length - 1];
        $(lastBlock).css("display", "none")
        jQuery('#showMoreAnchor').fadeIn(300);
    };

    var _divCount = jQuery('div.commentsWrapper > div').length;
    if (_divCount > 4) {
        jQuery('.showMoreAnchorWrapper').fadeIn(300);
    }

});

Answer №2

If you want to implement this functionality, simply insert the following code into the click event for #postButton:

  // check if more button was clicked      
  if (jQuery('div.commentsWrapper > div:visible').length > 4) {
    // fade out the last visible element
    jQuery('div.commentsWrapper > div:visible:last').fadeOut(300);
  }

For a live demonstration, visit the jsfiddle link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding the build ID in NextJS: A step-by-step guide

When working with NextJS, there's the option to generate a build ID as mentioned in the documentation here: https://nextjs.org/docs/app/api-reference/next-config-js/generateBuildId Alternatively, it is also possible to retrieve the build ID based on ...

What is the reason for receiving 'undefined' from await page.Evaluate() function call?

My attempt at creating a deploybot using nodejs is encountering an issue when trying to access the environments page, as it's unable to locate the button. The code snippet in question is as follows: //wait until element with unique id contain ...

An instructional guide on utilizing Python to extract the URLs of companies from a LinkedIn search

I'm having an issue extracting company profile URLs from a LinkedIn search as I keep getting a "not found" message. Despite my code running smoothly, the problem persists. Here is my code: import requests import csv import time import numpy from bs4 ...

When a fetch request is called inside a map function in React, the return

I attempted to retrieve a map array through fetch resolves so that each element inside favoriteCards would return a value and assign it to the test variable useEffect(() => { const test = favoriteCards.map((card) => { accuWeatherApi.getCurrentW ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

The Bootstrap Grid Leaves Blank Spaces Unfilled

View the screenshot here Take a look at the image above. I'm struggling to fill the empty space with div elements. I've experimented with display:inline-block and other display properties, but they haven't yielded the desired results. < ...

The Chrome Extension XHR always gets a 403 response except when it is triggered from the file:/// protocol

My current project involves the development of a Chrome Extension that relies on the fixer.io API for accessing currency exchange rates. To test this extension, I typically use a simple HTML page where I embed my JavaScript using <script> tags. When ...

When submitting, Redux objects are being submitted with empty values

Whenever I try to submit my form, the object is being submitted empty. This was confirmed using the redux dev-tool, where it shows that the object is empty upon submission. The expected behavior is for a card to appear on the DOM with the information enter ...

In JavaScript, is it possible to dynamically alter and showcase the value of a select tag?

My code snippet in the HTML file contains Javascript: <script> $(document).ready(function(){ $("#sub").click(function(){ var user_issue = $("#issue").val(); ...

Emphasize the center row within a moving table

I am interested in developing a scrolling table where only 10 rows are visible at any given time, with the middle row set to stand out even during scrolling. The concept is that as the user scrolls down, the highlighted row changes progressively as they c ...

I am experiencing a CSS display issue on the mobile version of my map leaflet where only the header and footer are visible

I am experiencing a display issue on Android and iPhone due to conflicting css commands. Here's what's happening: I am using React + React Leaflet with a header, main, and footer all set to width 100% within a parent div with body set to width an ...

Create a Bootstrap div containing a button that adjusts to different screen sizes on the

Struggling with an issue in Bootstrap on how to create an input group with responsive content and a button on the right side. I want the button to always be on the right side and also responsive. I attempted to achieve this with the code below, but it does ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Adjust the size of an element using the jQuery library's knob.js

There is a page Once the button is pressed, a circle element from the library jquery.knob.js appears. I am trying to change the size of the circle and have written this code: <div style="float:left; width:255px; height:155px"> <input ...

Retrieving JSONP data from Wunderground using jQuery

Having trouble parsing data from the "wunderground" API using JavaScript and Ajax. Some values are returned successfully, while others are not. Here is the link to the API I am utilizing: { "forecast":{ "simpleforecast":{ "forecastday":[ ...

Once AJAX has successfully retrieved the data

I am exploring the option of using jQuery ajax to fetch data from a database and display it asynchronously. However, I am faced with the challenge of achieving this without refreshing the entire page each time. For instance, the PHP file called during an ...

Rendering a js.erb partial from one js.erb file to another using Rails and Jquery

Currently, I am facing a situation where I have duplicate js.erb code in the ajax responses of different models. To avoid this redundancy, I am looking to refactor the duplicate js.erb code by passing arguments into a js.erb partial. Can anyone guide me o ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

Managing access to HTML pages on Tomcat 5.5 through tokens

My server is running Tomcat 5.5 and it hosts several HTML pages that I want to restrict access to. In order to do this, I need to implement a system where users' HTTP requests are checked for specific authentication values. I am looking to create a f ...

Alignment of inputs remains stubbornly off-center despite floating left

My main goal is to have all my inputs aligned to the left for a clean and organized look, similar to the image provided below: Despite my efforts to float the inputs and paragraphs to the left, I am facing an issue where they do not align properly. Instea ...