Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 Transitions are applied instantaneously on Cloned Elements

I have some elements that I'm applying CSS3 Transitions on by adding a new class.

HTML

<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;
}

jQuery

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

When I clone the .child element before adding the new class, and then I add the new class, transitions are applied immediately, not after 4sec.

Check out this fiddle.

like image 695
Ali Bassam Avatar asked Mar 03 '14 09:03

Ali Bassam


2 Answers

As I mentioned here:

If you want to set a delay between elements to trigger the transition, you can use .queue() and .dequeue() methods as follows:

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

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

WORKING DEMO

Updated

Per your comment, you should remove the .end class from the cloned elements when you remove the children by $("#remove").click().

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

The reason is you've defined the clone in global scope. Thus the cloned elements will have the .end class after adding the class by $(this).addClass("end").

UPDATED DEMO.

like image 64
Hashem Qolami Avatar answered Oct 07 '22 07:10

Hashem Qolami


You need to add a little timeout, the document gets altered too fast:

var clone;

$(window).load(function(){
     clone = $("#parent").children("div").clone();
     $("#parent").children("div").addClass("newChild");
});

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

$("#generate").click(function(){
    $("#parent").append(clone);
    setTimeout(function() {
        $("#parent").children("div").addClass("newChild");
    }, 30);

});

jsfiddle

like image 29
Alex Avatar answered Oct 07 '22 07:10

Alex