<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling for Dynamic Elements</title>
<style>
body {
display: grid;
justify-content: center;
font-family: sans-serif;
}
#container .itemContainer {
width: 400px;
height: 325px;
border: 5px solid #d9d9d9;
background-color: #f4f4f4;
border-radius: 5px;
overflow: auto;
}
#container button {
margin-top: 15px;
border: 5px solid #be2d21;
border-radius: 5px;
padding: 10px;
font-weight: bold;
font-size: 16px;
background-color: #E63B2E;
color: white;
transition: all .2s ease-out;
cursor: pointer;
}
#container button:hover {
background-color: #222;
border-color: #000;
}
#container .item {
margin: 20px;
padding: 10px;
background-color: #FAFF81;
border-radius: 5px;
transition: all .2s cubic-bezier(0.175, 0.885, 0.32, 1.275);
overflow: hidden;
height: auto;
filter: drop-shadow(0px 5px 8px #666);
}
#container .item:hover {
cursor: pointer;
background-color: #FFF;
transform: scale(1.02) translateY(-5px);
filter: drop-shadow(0px 10px 12px #666);
}
#container .removing {
animation-name: fadeOut;
animation-duration: .2s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(.44, .04, 1, .11);
pointer-events: none;
cursor: unset;
}
#container span {
pointer-events: none;
}
@keyframes fadeOut {
100% {
opacity: .5;
height: 0px;
padding-top: 0;
padding-bottom: 0;
margin-top: 0;
margin-bottom: 0;
}
}
</style>
</head>
<body>
<div id="container">
<h1>Add / Remove Items</h1>
<div class="itemContainer">
</div>
<button id="addItem">Add Item</button>
</div>
<script>
let itemElement = document.querySelector("#addItem");
let itemContainer = document.querySelector(".itemContainer");
itemElement.addEventListener("pointerdown", addSingleItem, false);
function addSingleItem(event) {
let randomNumber = Math.round(Math.random() * 100);
itemContainer.innerHTML += `<div class="item"><span>I am random number <b>${randomNumber}!</b></span></div>`;
}
itemContainer.addEventListener("pointerdown", startRemovingSelectedItem, true);
itemContainer.addEventListener("animationend", removeElement, false);
function startRemovingSelectedItem(event) {
let selectedElement = event.target;
if (selectedElement.classList.contains("item")) {
selectedElement.classList.add("removing");
}
}
function removeElement(event) {
event.target.remove();
}
function start() {
for (let i = 0; i < 3; i++) {
addSingleItem(null);
}
}
start();
</script>
</body>
</html>
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.