Event Delegation is a powerful technique in JavaScript that allows you to manage events efficiently by attaching a single event listener to a parent element rather than adding multiple listeners to individual child elements. This approach is widely used in modern web applications, including frameworks like React, to improve performance and scalability.
Event Delegation solves this by attaching one listener to a common ancestor (parent container) and handling events for all child elements that trigger it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Delegation Bit Validator</title>
<style>
body{
font-family: Arial, sans-serif;
background:#f4f6f9;
margin:40px;
}
.container{
max-width:600px;
margin:auto;
background:white;
padding:30px;
border-radius:8px;
box-shadow:0 3px 12px rgba(0,0,0,0.1);
}
input{
width:100%;
padding:12px;
border:1px solid #ccc;
border-radius:5px;
margin-top:10px;
}
.valid{ border:2px solid #2ecc71; }
.invalid{ border:2px solid #e74c3c; }
.message{
margin-top:12px;
font-weight:bold;
}
.success{ color:#2ecc71; }
.error{ color:#e74c3c; }
</style>
</head>
<body>
<div class="container" id="container">
<h1>Real-Time Bit Input Checker</h1>
<p>Enter bits separated by commas (example: <strong>1,0,1,1</strong>)</p>
<input type="text" placeholder="Input 1">
<input type="text" placeholder="Input 2">
<input type="text" placeholder="Input 3">
<div id="message" class="message"></div>
</div>
<script>
const container = document.getElementById("container");
const message = document.getElementById("message");
container.addEventListener("input", function(event){
// Check if the event came from an input field
if(event.target.tagName !== "INPUT") return;
const field = event.target;
const value = field.value.trim();
if(value === ""){
message.textContent = "";
field.classList.remove("valid","invalid");
return;
}
const bitsArray = value.split(',').map(bit => bit.trim());
const validBits = bitsArray.every(bit => bit === "0" || bit === "1");
if(!validBits){
message.textContent = "Only 0 and 1 are allowed.";
message.className = "message error";
field.classList.add("invalid");
field.classList.remove("valid");
return;
}
if(bitsArray.length % 2 === 0){
message.textContent = "✓ Valid input: Even number of bits.";
message.className = "message success";
field.classList.add("valid");
field.classList.remove("invalid");
}
else{
message.textContent = "✗ The number of bits must be even.";
message.className = "message error";
field.classList.add("invalid");
field.classList.remove("valid");
}
});
</script>
</body>
</html>
Output