<ul class="list" aria-live="assertive">
<li class="list-container show" >
<div class="list-item show">List Item</div>
</li>
<li class="list-container show">
<div class="list-item show">List Item</div>
</li>
<li class="list-container show" >
<div class="list-item show">List Item</div>
</li>
<li class="list-container show" >
<div class="list-item show">List Item</div>
</li>
</ul>
<button class="add-btn">Add New Item</button>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
line-height: 1.2;
}
body{
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 1rem;
}
.list{
list-style: none;
}
.list-container{
list-style: none;
text-align: center;
font-size: 3.5rem;
width: 300px;
height: 0;
position: relative;
cursor: pointer;
overflow: hidden;
}
.list-container.show:not(:first-child){
margin-top: 10px;
}
.list-container .list-item{
padding: 2rem 0;
width: 100%;
background-color: lightgray;
position: absolute;
opacity: 0;
top: 0;
left: 0;
transition: all 0.6s ease-out;
}
.list-container .list-item.show{
opacity: 1;
}
.add-btn{
background-color: transparent;
border: 1px solid black;
margin-top: 10px;
width: 300px;
text-align: center;
cursor: pointer;
padding: 2rem 0;
font-size: 2.5rem;
}
const addBtn = document.querySelector('.add-btn');
const list = document.querySelector('.list');
const listItems = document.querySelectorAll('.list-item');
function calculateHeightOfListContainer(){
const firstListItem = listItems[0];
let heightOfListItem = firstListItem.clientHeight;
const styleTag = document.createElement('style');
document.body.prepend(styleTag);
styleTag.innerHTML = `.list-container.show {
height: ${heightOfListItem}px;
}`;
setTimeout(function(){
styleTag.innerHTML += `.list-container {
transition: all 0.6s ease-out;
}`;
}, 0);
};
calculateHeightOfListContainer();
function removeListItem(e){
let container = e.target;
while(!container.classList.contains('list-container')){
container = container.parentElement;
}
container.classList.remove('show');
const listItem = container.querySelector('.list-item');
listItem.classList.remove('show');
container.ontransitionend = function(){
container.remove();
}
}
//DOCUMENT LOAD
document.querySelectorAll('.list .list-container').forEach(function(container) {
container.onclick = removeListItem;
});
addBtn.onclick = function(e){
const container = document.createElement('li'); container.classList.add('list-container'); container.setAttribute('role', 'listitem');
const listItem = document.createElement('div'); listItem.classList.add('list-item'); listItem.innerHTML = 'List Item';
container.append(listItem);
addBtn.parentNode.insertBefore(container, addBtn);
container.onclick = removeListItem;
setTimeout(function(){
container.classList.add('show'); listItem.classList.add('show');
}, 15);
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.