JSFiddle - React, Tailwind, and code Playground
by gweax
HTML
<p>
This paragraph has an event listener for a custom event that will set the text color to hotpink in the bubbling phase.<br>
It also has an event listener that will set the background color to antiquewhite in the capturing phase.
</p>
<button type="button">
Fire custom event!
</button>
JavaScript
document.querySelector('p').addEventListener('myevent', function (event) {
this.style.color = 'hotpink';
}, false);
document.querySelector('p').addEventListener('myevent', function (event) {
this.style.backgroundColor = 'antiquewhite';
}, true);
document.querySelector('button').addEventListener('click', function (event) {
// fire in a timeout to bypass any possible linkl between the click event and the custom event
setTimeout(function () {
var customEvent = new CustomEvent('myevent');
document.querySelector('p').dispatchEvent(customEvent);
}, 100);
}, false);