Edit: This question is similar to others (as commented by @jonathan-lonowski), regarding how to attach event handlers to dynamically created elements. However, my problem was that I didn't perceive that part of how event handlers are being bound to specific elements at one time during script execution - rather I thought of the event handlers as listening to all events, independent of the elements. Not knowing the root of the problem, I also didn't know what terms to search by. In retrospect, I see the other questions regard the same problem.
I am struggeling to understand why jQuery won't handle a class-directed event, unless the event handler is placed inside another event handler.
This code below is inspired from the jQuery course on sololearn.com, but no explaination is given there of why the click-on-remove-button event handler is placed within the click-on-add-button event handler.
When I try to move the event handler block for the remove-button-class-click, so as to stand before or after the event handler block for the add-button-click, there's no response upon clicking a remove-button.
I suspected it failed to work because :this didn't refer to the correct object. But from experimenting with alert(), it seems to me that :this is refering to the select-action context which fires the anonymous function, and it shouldn't matter where the event handler i placed within the root $(function(){}); clause.
Maybe I am missing something obvious? I am new to jQuery, but the logic of the event handling doesn't seem clear to me. The tutorials that I've been to don't give me the answer. Thanks!
HTML part:
<html>
<head>
<title>My To-Do List</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<div width="500px">
<h1>My To-Do List</h1>
<p>
<input id="value" type="text" placeholder="New Item" autofocus />
<button type="button" id="btn_add" class="action" name="add_btn">Add</button>
</p>
<p>
<ol id="my_list">
<!-- list-items get dynamically added here -->
</ol>
</p>
</div>
</body>
</html>
JS part:
$(document).ready(function(){
$("#btn_add").on("click", function(){
var val = $("#value").val();
if (val !== "") {
var new_e = $("<li></li>").text(val);
$(new_e).append("<button class='rem' name='rem_btn'>X</button>");
$("#my_list").append(new_e);
$("#value").val("");
$(".rem").on("click", function(){
$(this).parent().remove();
});
}
});
});