Skip to content

Instantly share code, notes, and snippets.

@hoangtranson
Created May 31, 2020 07:46
Show Gist options
  • Save hoangtranson/6e116da240c2dfea598ae83649742c6d to your computer and use it in GitHub Desktop.
Save hoangtranson/6e116da240c2dfea598ae83649742c6d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="grandparent">
<div class="parent">
<div class="child">Click child</div>
</div>
</div>
<script>
function addEvent(el, event, callback, isCapture = false) {
if (!el || !event || !callback || typeof callback !== 'function') return;
if (typeof el === 'string') {
el = document.querySelector(el);
};
el.addEventListener(event, callback, isCapture);
}
addEvent(document, 'DOMContentLoaded', () => {
const child = document.querySelector('.child');
const parent = document.querySelector('.parent');
const grandparent = document.querySelector('.grandparent');
addEvent(child, 'click', function (e) {
console.log('child');
}, true);
addEvent(parent, 'click', function (e) {
console.log('parent');
}, true);
addEvent(grandparent, 'click', function (e) {
console.log('grandparent');
}, true);
addEvent(document, 'click', function (e) {
console.log('document');
}, true);
addEvent('html', 'click', function (e) {
console.log('html');
}, true)
addEvent(window, 'click', function (e) {
console.log('window');
}, true)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment