I
I
Ilya Famin2021-06-10 12:58:33
JavaScript
Ilya Famin, 2021-06-10 12:58:33

Events not working for dynamically created elements?

When a button is clicked, an element should be created and it would seem that everything works, but the events associated with the classes of this element do not work

$('.add-newPost-bth').on('click', function(){
    $(`<div class="newPost">
        <div class="form-new-post">
            <form class="field-form-new-post">
                
            </form>
        </div>
        <script>
            autosize($('.textaria-new-post'));
        </script>
    </div>`).insertAfter('.newPost')
})

PS Content has been scaled down for readability. Methods from the category to add live (), setTimeout, etc. did not help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-06-10
@Fama18122000

Use event bubbling.

$(document).on('click', '.add-newPost-bth', function() {
  ...
});

Instead of document, you can substitute the selector of any static parent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question