How can we add a class to div elements that are dynamically fetched using AJAX in HTML?

I am including additional HTML content upon clicking a "load more" button using the following JavaScript function:

function addStuff() {
  $.get('page-partials/more-stuff.html', function(stuff) {
    $('#load-button').append(stuff);
  });
};  

The issue I'm encountering is that this new content is inserted into a container with a varying height, and I would like to animate it downwards as more items are added. To achieve this effect, I need to assign a dynamic class to the divs inside 'more-stuff.html' every time that template is appended.

For example:

<div class='stuff added1'></div>

Subsequently, on the next iteration:

<div class='stuff added2'></div>

Is there a way to accomplish this? Alternatively, does anyone have suggestions for animating changes in height from an unknown nonzero value to another unknown nonzero value?

Answer №1

How about this?

let total = 0;
$.get('page-partials/additional-things.html', function(things) {
    total++;
    $('#load-btn').append(things).addClass('new-thing added'+total);
});

Answer №2

Interestingly, Vivek proposed an alternative approach that looks something like this:

var element = '<div style="height:200px;">Dynamically appended div</div>'; // ajax response
var height = $(element).height(); // determine the height
$('.element').append(element).css('height', height); // update the height after appending
.element {
    height:60px;
    width:100px;
    border:2px solid #f00;
    -webkit-transition: height 0.8s ease-in-out;
    -moz-transition: height 0.8s ease-in-out;
    -o-transition: height 0.8s ease-in-out;
    transition: height 0.8s ease-in-out; /* CSS3 transition for animating height */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='element'></div>

Answer №3

To enhance the functionality, consider using the added function in conjunction with each call to addStuff

function addStuff() {
  // Obtain a jQuery promise object by returning from `addStuff`
  return $.get('page-partials/more-stuff.html', function(stuff) {
    $('#load-button').append(stuff);
  });
}; 

var added = function() {
  $(".stuff").each(function(index) {
    $(this).addClass("added" + index + 1)
  })
}

addStuff().then(added);

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

Strange behavior in Angular 4 routing: Child module not rendering unless the page is manually refreshed

I've been trying to find a solution for this strange behavior but haven't had any success. There are no errors showing in either the Angular 4 console or the JavaScript console. Currently using Angular CLI (Angular 4). I'm encountering ...

You must use the 'new' keyword to invoke the class constructor NextResponse | Implementing middleware in Next.js | Implementing role-based protection for routes in Next.js |

I've been working on implementing user role-based protected routes in my next.js project using middleware.js, but all of a sudden, I've encountered this issue. I'm not exactly sure why this is happening, so if anyone has a better approach to ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Having trouble vertically aligning text in Bootstrap 4?

I'm having trouble getting the text to align vertically in the middle and closer to the image. The vertical-align:middle property doesn't seem to be working for me. Additionally, when I resize the screen width, the layout changes from a horizonta ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Issues with form_valid in django

https://i.sstatic.net/xj0Ys.pngIn my Django project, I am utilizing a Class-Based View (CBV) with Detail View and FormMixin to handle the functionality of listing posts and creating comments. However, I am encountering an error, as shown in the image, when ...

Chromium CSS blend mode problem

Can anyone help me create a Photoshop overlay effect on my website? My code works perfectly in Firefox, but it's not functioning correctly in Chrome. Here's the demo. This is my current code: HTML <img src="http://lorempixel.com/output/fash ...

Generating a continuous visual display using a dynamic div with looping animation in JavaScript

Hey there, I could really use some assistance. I am currently working on a project that involves creating 100 identical divs (rows) with four inner divs (columns) inside each one containing either an image or text. The first column in each row should have ...

Utilize AJAX to extract JSON data

This is the JavaScript code I am working with: function process_file(file_name) { $.ajax({ type: "POST", url: "process_file.php?file_name="+file_name, datatype : "json", cache: true, success: function(data) { ...

Tips for Sending Props While Utilizing CSS Modules

I've been working with a button component that utilizes the Tailwindcss framework and css modules for some extra styling. It currently looks like this, incorporating template literal to integrate the red background styling. CSS Module: .red { back ...

What steps are necessary to facilitate payments through Stripe instead of directly on my Wordpress website?

On my Wordpress website, I have created a page where users can select a subscription offer. Currently, the layout looks like this: https://i.sstatic.net/qltbU.png My goal is to redirect users to a Stripe payment page when they click on any of the subscrib ...

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Having trouble finding the ./.env file in Gatsby. Encountering an env-cmd error

Having trouble with a file named .env.development in the root folder. I installed env-cmd as a dev dependency and when trying to start the server > npm run develop it gives me an error > <a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Guide to positioning front layer in CSS3

I am currently working on a page and have added an "Under Construction" banner to indicate it is not yet finished. Could someone assist me in bringing the png to the forefront on this link? ...

Is there a way to customize the email content for Opencart orders according to our preferences? Can we make changes to it

Is it possible for me to modify the content of the order email? Which specific file should I refer to for this? This is a confirmation of an online transaction made with ######. The AuthOnly transaction amounted to $171.90 and will soon be processed to y ...

Is it possible to access the serial port using HTML5?

Can a HTML5 page access the serial port of a device solely on the client-side? I am aware that this is possible with Java applet, but I am curious to know if it can be achieved using HTML5. ...

Exploring sections on a Three.js Cylinder

Playing around with Cylinder Geometry from Three.js is so much fun! You can check out the documentation here. Here's my CodePen where I've been experimenting: https://codepen.io/lklancir/pen/pdaPoY var gui = new dat.GUI(); var s ...

Content in tab remains stagnant

I am having trouble creating different tabs on a page with unique content in each tab's body. Whenever I click on a new tab, the body content remains the same. I'm not sure if it's an issue with how the tabs are set up in the HTML or if ther ...

Apollo Server Studio is failing to detect the schema configured in Apollo setup

Here is the stack I'm working with: Apollo Server, graphql, prisma, nextjs I've set up a resolver.ts and schema.ts for my graphql configuration under /graphql resolver.ts export const resolvers = { Query: { books: () => books, } ...

Checking a condition with a for loop in Javascript

I'm working on developing a function that can generate a random number between 0 and 9 that is not already included in an array. Here is the code I have come up with so far: var myArr = [0,2,3,4]; console.log("Array: " + myArr); function newN ...