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

Having trouble with redirecting a website to its appropriate version for mobile or desktop users?

After creating both the desktop and mobile versions of my website, I have a question. How can I determine whether a visitor is using a mobile phone or a PC when they come to my website? Specifically, if a visitor accesses my website through a mobile devic ...

Django and Ajax working together with GET requests

Despite having experience in working with Python, Django, and REST framework, I am facing a challenge when trying to make an Ajax request. No matter how many similar questions I come across, I just can't seem to solve the problem at hand. The situatio ...

I am facing difficulties installing packages such as react-bootstrap on my dashboard

Encountering an issue with installing packages in my dashboard. For example, attempting to install react-bootstrap results in the following error: node version: 12.16.1 npm version: 6.13.4 gyp ERR! UNCAUGHT EXCEPTION gyp ERR! stack Error: Cannot find mo ...

Unable to populate SQL Server database from PHP JQuery form

I am facing an issue where hitting save just refreshes the page with a different URL added. Uncertain if it's due to my query or if the form data is not being submitted correctly. require_once ('connectionstring/connectionstring.php'); $con ...

Dropdown for state selection within WooCommerce for specific countries

I am encountering a challenge in configuring a form with default WooCommerce country and states selection dropdowns. Essentially, my goal is to present the Country selection first, followed by the State selection based on the chosen country. For instance, ...

Google maps are failing to display on the page when loading via ajax

When I click a button, I use AJAX to load a page, but the map on the loaded page is not displaying. There are no errors showing up either. I have tried adding initmap() after the ajax load, but it doesn't work. Do I need to bind it somehow? What am I ...

What is the best way to pass an Id to JavaScript's getElementById when the Id from my input tag is produced by the output of PHP/MySQL?

Thank you in advance for your assistance. I am attempting to search through all the IDs listed below to determine if the user has selected any data. <input id=\"".$row['childName']."\" type=\"checkbox\" name=\"foodDa ...

Creating a Website that Adapts to Different Browser Sizes: Tips and Tricks

I am currently working on a website that features a video background (mp4 file). However, I noticed that the video appears differently in Chrome, Explorer, and Firefox. In order to ensure compatibility across all browsers, I need to make some adjustments i ...

Trouble with loading Google chart data from a local JSON file

The Issue Running multiple charts on a site simultaneously is causing page blocking while loading all the data before rendering the charts. The goal is to trigger the render function for each chart as soon as the data is available, rather than waiting for ...

Ensuring continuity of session in WebRTC audio calls post page refresh

Currently, I am utilizing the Kandy WebRTC library to facilitate audio calls through WebRTC. One issue I have encountered is maintaining the session alive if a user refreshes the page, as this JavaScript library operates internally using WebSocket. For in ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Restrict the height of a division based on the adjacent division

Within the parent div, I have two child div elements that are meant to be positioned side by side. The first element contains an image which loads dynamically, meaning its height is unknown in advance. I want the parent div's total height to match the ...

Is there a clash between jquery_ujs and Kaminari AJAX functionality in Rails 4?

After some investigation, it seems that there is a conflict between jquery_ujs and Kaminari's AJAX support in my Rails 4 application. Within my application.js file, I have included the following: //= require jquery //= require jquery_ujs //= require ...

Using Selenium to interact with a Modal Dialog window

When trying to navigate to a page in IE9 using Selenium, a certificate error message appears on the page. By using AutoIT, I am able to click within the browser, TAB twice, and hit enter without any issues. However, after this step, an error for a "Modal d ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

Having trouble connecting to the webserver? Make sure the web server is up and running, and that incoming HTTP requests are not being blocked by a firewall

While working on my Visual Studio 2013 Asp.Net web code using the Local IIS Web server Version 7 (Windows 7 x64) and Framework 4.0, I encountered an error message stating: "Unable to start debugging on the web server. Unable to connect to the webserver. V ...

Display the JSON data by pressing Enter key instead of clicking on the submit button

I am facing an issue with my MVC view where clicking the submit button posts data using Ajax to the Controller. The controller returns a JSON result containing messages which are then displayed on the View. The problem arises when I press Enter after seein ...

Exploring the Contrast between 'this' Context in V8 Javascript: Chrome versus Node.js

Check out the code snippet below: var pocket = { cash: 1000, showCash: function() { return this.cash; } }; var thomas = { name: "Thomas", work: function() { console.log('I don&bs ...

Sending an error code that is specific to the situation to the AJAX error function

I am attempting to send a custom error code to the client-side for ajax error handling. On the server side: $response = array(); if ( empty($post['parent_id']) ) { $response = array('error' => true, 'status_code' => ...

Exploring the connected component feature in React/Redux

While testing the connected component of my React/Redux app, I encountered an error. The test case that caused the error is: App component › shows account info and debits and credits` Invariant Violation: Could not find "store" in either the context or ...