0

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?

Gwendal Grelier
  • 526
  • 1
  • 7
  • 21
  • 1
    When the event listener is registered, the buttons do not exist. Try listening to ```$(document).on("click", ".my_btn", ...``` – Tim VN Jan 28 '20 at 11:05
  • 1
    You need add your event handler to the element *after* it is added to the DOM. Alternatively, and more simply, use a delegated event handler: `$('#btn_content').on('click', '.my_btn', function () {... ` – Rory McCrossan Jan 28 '20 at 11:06

0 Answers0