Tips for implementing a slide up animation on a dynamic element

I have one div and a button.

When the button is clicked, I am appending another div. After appending the second div, I want to add a slide-up animation to the first div and a slide-down animation to the second using jQuery.

<div class="main">
    <div class="user">
        <div class="closed_div">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <button class="addDiv">Add open Div</button>
</div>

Now, I am appending the new div using the code below

$(document).ready(function(){
            $('.addDiv').click(function(){
                var html = '<div class="open_div">Lorem Ipsum is simply dummy text of the printing and \n\
                        typesetting industry. Lorem Ipsum has been the industrys \n\
                        standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type \n\
                        specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining \n\
                        essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, \n\
                        and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>';
                $('.user').append(html);
            });
        });

And animate with the following code

$(".closed_div").animate({height:'100%','opacity':1},1500);
$(".open_div").animate({height:0},1500);

However, it's not working well. Can you suggest what I might be doing wrong?

Thank you.

Answer №1

Check out this jQuery implementation using slideUp and slideDown functions to toggle div elements. By removing the slid up divs, you can prevent animation glitches that may occur due to height:100% settings.

let counter = 0;

$('.addDiv').click(function() {
  var html = $('<div class="closed_div">Lorem Ipsum is simply dummy text of the printing and \n\
                        typesetting industry. Lorem Ipsum has been the industrys \n\
                        standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type \n\
                        specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining \n\
                        essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, \n\
                        and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.' + counter++ + '</div>');
  $('.user div').slideUp(300, function() {
    $( this ).remove();
  });             
  $('.user').append(html);
  html.slideDown();
  
});
.closed_div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <div class="user">
    <div class="open_div" style="display:none;">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
      and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
  </div>
  <button class="addDiv">Add open Div</button>
</div>

Answer №2

$(".closed_div").animate({height:'100%','opacity':1},1500);  
  $(function () {
   $('.addDiv').click(function(){
        var elem = $(this);
        $('.user').after('<div class="open_div none">Lorem Ipsum is simply dummy text of the printing and \n\
typesetting industry. Lorem Ipsum has been the industrys \n\
standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type \n\
specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining \n\
essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, \n\
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>').next('div').slideDown('slow');
    });
});
.none{
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
    <div class="user">
        <div class="closed_div">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <button class="addDiv">Add open Div</button>
</div>

Answer №3

To hide the newly appended open_div, you must apply the display none property. Additionally, assign the closed_div class to the previously opened div and use slideUp to conceal the last closed_div. After the slideUp callback function, employ slideDown on the most recent open_div.

In your CSS file, ensure that display: none is set for the open_div

$(document).ready(function(){
            $('.addDiv').click(function(){
                var html = '<div class="open_div">Lorem Ipsum is simply dummy text of the printing and \n\
                        typesetting industry. Lorem Ipsum has been the industrys \n\
                        standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type \n\
                        specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining \n\
                        essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, \n\
                        and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>';
                $('.open_div:last').addClass('closed_div');
                $('.user').append(html);
                $('.closed_div:last').slideUp("slow", function() {
                $('.open_div:last').slideDown("slow");
                });
            });
        });
.open_div {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
    <div class="user>
        <div class="closed_div">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <button class="addDiv">Add open Div</button>
</div>

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

AngularJS ng-map defines the view position using rectangular coordinates

Is there a way to set the position of ng-map view using the ng-map directive not as the center value of [40.74, -74.18], but instead as a rectangle defined by the corner values of the map view (north, south, east, west)? Currently, I have this code: < ...

Free up Object Three.js

I've been working on a project that utilizes webGl and Three.js. The main issue I'm facing is related to memory deallocation. As the game progresses, a large number of objects are created, leading to excessive memory allocation. Despite trying v ...

Ways to conceal the header and footer on specific React pages

I currently have my header and footer wrapping the content on all pages of my website. However, I am looking to hide the header and footer on specific pages like the customer and admin dashboard. Can anyone suggest the best approach to achieve this? cons ...

.eslintignore not functioning as intended

Recently, I started working on a Vue template project that includes ESLint. However, I found that I wanted to disable ESLint for some reason. To do this, I followed the recommended steps and created a file with the following content: **/*.js This file wa ...

AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page. The initial list items are generated through ng-repeat, with the second to last item containing a span. When t ...

Issues with Twitter Bootstrap Tabs not functioning correctly on Ruby on Rails with HAML

I am facing an issue with twitter bootstrap tabs in my (HAML) ruby on rails project. Although the tabs are appearing, the content does not change when I click on different tabs. Additionally, some unexpected statements are showing up at the bottom of the f ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

What is preventing the use of data post submission in React JS?

After posting data to the navigation, I retrieve it and then use the following code: .then(data => console.log(data.PathPDF)) .then(data => window.open(data.PathPDF, '_blank', 'noopener,noreferrer')); While I can successfully ret ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

Rectangles in collision: A mathematical analysis

After numerous attempts, I have developed a small "game" that incorporates collision detection. Unfortunately, I have encountered a persistent issue where objects sometimes pass through each other. The root cause of this problem eludes me completely. Ini ...

Utilizing jQuery to eliminate spaces and prevent special characters: a comprehensive guide

For my website's signup form, I need to enforce certain rules for the username: The username cannot contain any spaces. The username can only include a dot (.) as special character, similar to how Gmail handles usernames in their signup form. I am ...

Creating a Typescript project that compiles to UMD format, however, encountering the challenge of

I am trying to convert my index.ts file into a UMD index.js so that I can use it with a <script> tag. Here is the TypeScript configuration I am using: { "compilerOptions": { "outDir": "dist", "declaration& ...

Prevent the row height from fluctuating following the fadeOut() effect

Currently, I am facing an issue with two elements on my page: .start_over_button and .speed_buttons. In CSS, the .start_over_button is set to display: none, and in my JavaScript code, I have it so that when .speed_buttons are clicked, they fade out and the ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

load a particular section of another website into my own div

Similar Question: Ways to bypass the same-origin policy I've been looking for a way to load a specific div from another website using this code. Can anyone provide an example of how to do this on jsfiddle? $.ajax({ url: 'http://somethin ...

Tips for confirming that the text in a particular element is visible on the page when utilizing Selenium IDE

I'm stuck on a question that I can't figure out. Could someone help me locate the current element displayed below: <td style="width: 250; text-align:right" class="stData"> March 14 2014, 00:00 </td> that specifically includes the t ...

How can I create a DIV element that consistently shows text when clicked?

Is there a way to achieve this effect using just CSS and HTML? When clicking on the question text, it should reveal the answer below, and clicking again should hide the answer. I have managed to make it work with hover, but I am unsure how to implement it ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

Tips for eliminating the glowing effect when pressing down on the thumb of the material ui slider

Visit Material-UI documentation for Slider component. Despite setting the disabled flag for the entire slider, the thumb continues to show a halo effect when clicked. ...