Last active
October 25, 2019 10:00
-
-
Save rainjeck/65477c2760a79f6f3cb85aa456482c50 to your computer and use it in GitHub Desktop.
Event Delegation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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