Skip to content

Instantly share code, notes, and snippets.

@aleroddepaz
Last active July 28, 2021 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleroddepaz/92aef780a795a8b780d0 to your computer and use it in GitHub Desktop.
Save aleroddepaz/92aef780a795a8b780d0 to your computer and use it in GitHub Desktop.
<!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>&times;</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('&times;')
).appendTo(list);
input.val('');
return false;
});
</script>
</body>
</html>
<!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 = "&times;";
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