[javascript] What is DOM Event delegation?

Event Delegation

Attach an event listener to a parent element that fires when an event occurs on a child element.

Event Propagation

When an event moves through the DOM from child to a parent element, that's called Event Propagation, because the event propagates, or moves through the DOM.

In this example, an event (onclick) from a button gets passed to the parent paragraph.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
    $(".spoiler span").hide();_x000D_
_x000D_
    /* add event onclick on parent (.spoiler) and delegate its event to child (button) */_x000D_
    $(".spoiler").on( "click", "button", function() {_x000D_
    _x000D_
        $(".spoiler button").hide();    _x000D_
    _x000D_
        $(".spoiler span").show();_x000D_
    _x000D_
    } );_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="spoiler">_x000D_
    <span>Hello World</span>_x000D_
    <button>Click Me</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Codepen

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to event-delegation

Delegation: EventEmitter or Observable in Angular What is DOM Event delegation?