Search code examples
javascriptjqueryevent-handlingjquery-events

What's the best way to event handle dynamically created HTML?


It's very easy to event-handle when dealing with items the document has from the get go:

$(document).ready(function() {
    $('.element-in-question').on("event", function (event) {
        //do what you need to do during the event
    });
});

My problem is how would I best deal with dynamic elements. For example, let's say I dynamically load notifications, some of which are friend requests during an AJAX request. Would I create the event-handler in the success callback, or would I do it somewhere else?

The way I would currently go about it:

$(document).ready(function() {
    $.ajax({
        url: '/friendships/requests',
        type: 'GET', 
        success: function(responseData) {
            //dynamically create your elements (with classes accepted and rejected)
            $('.accepted, .rejected').on("click", function(event) {
                //do what is needed in this event
            });
        }
   });
});

Is this the idiomatic way to go about it, or is there another way I probably should be going about it?


Solution

  • use jquery's "on" merhod to bind event handler to parent element (which will not change) and pass a selector of the element you want to listen to:

    $('.parent').on('event', '.child', handlerFunction);