Last active
July 28, 2021 14:00
-
-
Save aleroddepaz/92aef780a795a8b780d0 to your computer and use it in GitHub Desktop.
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 charset="utf-8"> | |
<title>Event delegation example (with jQuery)</title> | |
<style> | |
button { margin: 5px; } | |
</style> | |
</head> | |
<body> | |
<div> | |
<form id="todo-form"> | |
<input id="new-todo"/><button>Add</button> | |
</form> | |
<ul id="todo-list"> | |
<li> | |
<span>Buy the milk</span> | |
<button>×</button> | |
</li> | |
</ul> | |
</div> | |
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> | |
<script> | |
var input = $('#new-todo'); | |
var list = $('#todo-list').on('click', 'button', function() { | |
$(this).parent().remove(); | |
}); | |
$('#todo-form').submit(function() { | |
$('<li>').append( | |
$('<span>').text(input.val()), | |
$('<button>').html('×') | |
).appendTo(list); | |
input.val(''); | |
return false; | |
}); | |
</script> | |
</body> | |
</html> |
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 charset="utf-8"> | |
<title>Event delegation example</title> | |
<style>button { margin: 5px; }</style> | |
</head> | |
<body> | |
<form id="todo-form"> | |
<input name="new-todo"/> | |
<button>Add</button> | |
</form> | |
<ul id="todo-list"/> | |
<script> | |
var todoList = document.getElementById("todo-list"); | |
function addTodo(text) { | |
if (!text) return; | |
var span = document.createElement("span"); | |
span.appendChild(document.createTextNode(text)); | |
var button = document.createElement("button"); | |
button.innerHTML = "×"; | |
var li = document.createElement("li"); | |
li.appendChild(span); | |
li.appendChild(button); | |
todoList.appendChild(li); | |
} | |
document.getElementById("todo-form").onsubmit = function() { | |
addTodo(this.elements["new-todo"].value); | |
this.reset(); | |
return false; | |
} | |
todoList.addEventListener("click", function(e) { | |
if(e.target && e.target.nodeName === "BUTTON") { | |
todoList.removeChild(e.target.parentNode); | |
} | |
}); | |
addTodo("Buy the milk"); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment