CSS3 Transition effects are applied immediately to duplicated elements

My dilemma lies in applying CSS3 Transitions to elements by introducing a new class.

Markup

<div id="parent">
   <div class="child">
   </div>
</div>

CSS

.child {
    background: blue;
    -webkit-transition: background 4s;
    -moz-transition: background 4s;
    transition: background 4s;
}

.newChild {
   background: red;
}

JavaScript/jQuery

$(".child").addClass("newChild");

My issue arises when I clone the .child element before adding the new class, as the transitions take effect immediately instead of after 4 seconds.

Feel free to explore this example.

Answer №1

Just as I previously stated here:

In order to create a delay between elements to activate the transition effect, you can utilize the .queue() and .dequeue() methods in this manner:

$("#generate").click(function() {
    $("#parent").append(clone);

    $("#parent").children("div").delay(4000).queue(function() {
        $(this).addClass("end").dequeue(); // proceed to the next queue task
    });
});

VIEW LIVE EXAMPLE

Update

Based on your feedback, it is advisable to eliminate the .end class from the duplicated elements when removing the children using $("#remove").click().

$("#remove").click(function(){
     $("#parent").children("div").remove();
    clone.removeClass('end');
});

The rationale behind this action is that the clone has been defined within the global scope. Consequently, the duplicated elements will retain the .end class even after applying the class with $(this).addClass("end").

UPDATED INTERACTIVE DEMO.

Answer №2

To prevent the document from being altered too quickly, consider adding a short timeout:

var newClone;

$(window).load(function(){
     newClone = $("#container").children("div").clone();
     $("#container").children("div").addClass("newElement");
});

$("#delete").click(function(){
     $("#container").children("div").remove();
});

$("#add").click(function(){
    $("#container").append(newClone);
    setTimeout(function() {
        $("#container").children("div").addClass("newElement");
    }, 30);

});

Check out the code on jsfiddle

Answer №3

In my opinion, utilizing

.delay(), .queue() and .dequeue()
is essential:

$("#activate").click(function(){
    $("#container").append(clone);
    $("#container").children("div").delay(1).queue(function() {
       $(this).addClass("freshChild").dequeue();
    });
});

Answer №4

Don't forget to set the transition on your newChild element:

.newChild {
    background: blue;
   -webkit-transition: all 2s;
   -moz-transition: all 2s;
   transition: all 2s;
}

Demo

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

Preventing selection of past dates with Material UI in ReactJS

I'm currently working on a date range picker using react material ui. The goal is to allow users to select a specific date and then disable all past dates from that selected date onward. How can I go about implementing this functionality in react mate ...

Tips on updating the $authProvider.loginUrl for Satellizer from an Angular controller

Consider this hypothetical situation: A user attempts to access a /settings page without being logged in. The Settings controller detects based on $auth.isAuthenticated() != true that the user is not logged in, and directs them to the /login page. The us ...

Active Arrow Link

I'm currently working on customizing the appearance of my WordPress site's categories sidebar by adding an arrow to the left side of the active link. After tweaking the CSS to achieve the desired behavior and making some color adjustments for te ...

Encountering download issues with the FileTransfer API on Android while using Phonegap

I'm currently working on incorporating the FileTransfer API into my Phonegap App using Javascript. However, when I use the code below to call it, I encounter the following error: 01-24 00:36:10.495: I/Web Console(14802): Error: SyntaxError: Unexpecte ...

What is the best way to delete a model from a Backbone.Collection?

How can I properly remove a model from a collection in Backbone.js? var item = new Backbone.Model({ id: "01", someValue: "blabla", someOtherValue: "boa" }); var list = new Backbone.Collection([item]); list.get("01").destroy(); After calling ...

After mapping in JavaScript, delete the property name

Is there a way to exclude the property name from the returned value? I want to eliminate the property name "projects: [ ]" from the output. router.get("/", (req, res, next) => { Project.find() .exec() .then(docs => { res.status(200) ...

What is the best way to adjust my content to be mobile-friendly with the Material UI drawer?

I am facing an issue with adjusting the content in Form.jsx based on the movement of the drawer. When I expand the Drawer by clicking on the menu icon, the content inside the body does not move along with it. How can I make sure that the content moves acco ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Retrieve the original jqXHR object from the success callback of the $.ajax function

My original task is as follows: Execute a jQuery.ajax() request. Upon success, perform additional checks on the data received from the server. If these checks fail, reject the promise for further handling. After researching extensively online, I came up ...

The child_process in Node is attempting to utilize /usr/bin/zsh, but unfortunately, it is unable to do so because

Recently, I've been encountering issues with several npm commands failing, accompanied by an error message that looks like this: npm ERR! code ELIFECYCLE npm ERR! syscall spawn /usr/bin/zsh npm ERR! file /usr/bin/zsh npm ERR! path /usr/bin/zsh npm ER ...

Update the state in the componentDidMount lifecycle method

Embarking on a project using React to hone my skills, but encountered an error while trying to populate an array with data from a JSON file in the ComponentDidMount() hook. It seems this issue stemmed from a previous error: cannot read property 0 of undef ...

The React button fails to refresh the display

I am working on creating a dynamic input form that, when clicking a button, will generate a new row of description input fields. To keep track of these descriptions, I am using an array within the state: state = { descriptions: [ { ...

The PNG image keeps getting cropped

The bottom of a PNG image is being cropped off. View the picture illustrating the issue .loadMoreBtn-label { background-image: url(picture); background-repeat: no-repeat; padding-left: 30px; background-size: 23px 23px; background-posit ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Exploring a JSON object and dynamically populating FormData with values using jquery

I am working with a JSON object in jQuery that looks like this: userObj = { "loginId":"abc123", "class":"5", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5e5457565311584b4c0e0606087f58525e5653115c5052">[e ...

Height adjustment for flexbox children

Can someone assist me with marking up a todo list? I am attempting to set the height of div.main-tasks equal to div.tasks so that the former fills the entire latter. Unfortunately, I am unsure how to achieve this. You can refer to the following image for c ...

Ongoing state configuration in a React hook

My custom hook: export function useToken2() { const { data: session, status } = useSession(); const [token, setToken] = useState<string | null>(null); useEffect(() => { if (status === 'authenticated' && session?.accessToken) { ...

Generate a purposely filled css grid with excessive content

I am attempting to design a horizontal scrolling widget that resembles an image carousel but with text and icons. This widget will contain multiple columns, but only one will be visible at a time while the others will have 'overflow: hidden'. T ...

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Create a sleek and uniform design with Bootstrap by setting up three columns that maintain the same height

I am attempting to design a 3 column div that maintains equal height for all responsive rows, each containing an ICON and information. <div class="container"> <div class="row row-eq-height"> <div class="col c ...