I am using AJAX to dynamically add a button to the DOM. This button is supposed to trigger a function on click but it's not.
Here is the MWE:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
<script src="script.js"></script>
</head>
<body>
<!-- The btn is added here -->
<div id="btn_content"></div>
</body>
</html>
btn.html
<button class="my_btn">Click here</button>
script.js
$(document).ready(function () {
// Adds the button to index.html
$.ajax({
type: "GET",
url: "btn.html",
dataType: "html",
success: function (html_text) {
$('#btn_content').html(html_text);
}
});
// Click event that is not triggerd
$('.my_btn').click(function () {
console.log("This is not working");
})
});
A similar issue was mentionned but not answered with a practical solution at the time. Submit button does not trigger on items added via ajax
Any thoughts?