CSS Animation on Element Dynamically Inserted to DOM

css
Published on March 10, 2021

Animation can be done on an element which is dynamically inserted to page using CSS animation property. This property allows to give an initial and the final state of an element, and perform an animation between those states.

CSS transition also can perform animations, however the initial & final states cannot be specified. animation property is a much easier way to implement this.

Example

Box

Download Code

HTML, Javascript & CSS

<div id="boxes">
	<div class="box">Box</div>
</div>
<button id="add-box">Add New</button>
// append new box on click
document.querySelector("#add-box").addEventListener('click', function() {
	let box = document.createElement('div');
	box.innerHTML = 'Box';
	box.classList.add('box', 'new-box');

	document.querySelector("#boxes").appendChild(box);
});
.box {
	background-color: #78e08f;
	padding: 10px;
	margin: 0 0 20px 0;
}

@keyframes append-animate {
	from {
		transform: scale(0);
		opacity: 0;
	}
	to {
		transform: scale(1);
		opacity: 1;	
	}
}

/* animate new box */
.new-box {
	animation: append-animate .3s linear;
}

Other Animation Types

Changing the @keyframes rules, the animation can be customized as per need.

  • #boxes {
    	overflow: hidden;
    }
    
    @keyframes append-animate {
    	from {
    		transform: translateX(-100%);
    		opacity: 0;
    	}
    	to {
    		transform: translateX(0%);
    		opacity: 1;
    	}
    }
    
    Box
  • @keyframes append-animate {
    	from {
    		transform: scaleY(0);
    		opacity: 0;
    	}
    	to {
    		transform: scaleY(1);
    		opacity: 1;
    	}
    }
    
    .new-box {
    	transform-origin: 50% 0;
    	animation: append-animate .3s linear;
    }
    
    Box
In this Tutorial
    Comments
    Loading Comments