Skip to content

Instantly share code, notes, and snippets.

@rainjeck
Last active October 25, 2019 10:00
Show Gist options
  • Save rainjeck/65477c2760a79f6f3cb85aa456482c50 to your computer and use it in GitHub Desktop.
Save rainjeck/65477c2760a79f6f3cb85aa456482c50 to your computer and use it in GitHub Desktop.
Event Delegation
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Event Delegation">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Event Delegation</title>
</head>
<body>
<ul></ul>
<script>
var ul = document.querySelector('ul');
for (var i = 0; i < 5; i++) {
var li = document.createElement('li');
var input = document.createElement('input');
var label = document.createElement('label');
input.setAttribute('type', 'checkbox');
input.setAttribute('value', 'Check ' + (i + 1));
input.setAttribute('id', 'check' + (i + 1));
label.setAttribute('for', 'check' + (i + 1));
label.innerHTML = 'Check ' + (i + 1);
li.appendChild(input);
li.appendChild(label);
ul.appendChild(li);
}
ul.addEventListener('click', toggle);
function toggle(e) {
if (!e.target.matches('input')) return;
console.dir(e.target);
if (e.target.checked) {
alert(e.target.value);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment