Delegation in JavaScript is the ability to handle child elements through a single parent. This flexible and convenient technique is used so that you don’t have to assign many child elements different IDs, but instead process actions on them through their parent element.
document.getElementById('menu').onclick = function (e) {
e.target // Returns the child DOM object on which the event occurred
e.currentTarget // Added for browser compatibility (supported in IE9+)
window.event.srcElement // Added to support the older IE < 9
e.clientX // Returns the mouse X coordinate at the moment the event fires
e.clientY // Returns the mouse Y coordinate at the moment the event fires
}
Goal: There is an unordered list:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
We need to make it so that when the mouse cursor hovers over each list element, its styles change (background, color, bold, etc.) When the mouse leaves the element, revert its styles to what they were before. Event delegation must be used – attach the handler to the main list element (ul). Use the classList property to add and remove classes.
Option 1 – handling via delegation and two functions
Create two functions: one for mouse‑over, one for mouse‑out.
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
</head>
<body>
<style>
#menu { list-style-type: none; width: 70px; }
#menu li { padding: 10px; }
.list-decor { border: 2px solid #eee; border-radius: 8px; font-weight: bold; font-size: 16px; padding: 5px; width: 50px; }
</style>
<ul id="menu">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
document.getElementById('menu').onmouseover = function (e) { // Attach handler
var event = e || window.event; // Get event.target (window.event added for old IE support)
var target = event.currentTarget || event.srcElement; // event.srcElement for old IE support
if (target.tagName == 'LI') { // Checking if a list item is hovered
target.classList.toggle("list-decor"); // Add class list-decor if not present
}
};
document.getElementById('menu').onmouseout = function (e) {
var event = e || window.event,
var target = event.currentTarget || event.srcElement;
if (target.tagName == 'LI') {
target.classList.toggle("list-decor"); // Remove class list-decor if present
}
};
</script>
</body>
</html>
Option 2 – delegation with a single function
Create one function that will change the class and styles depending on what we pass to it. On mouse‑over we pass one word, on mouse‑out another.