Firing an event when an item is created

I want to call a function on creation of new divisionsin the DOM (i.e. created dynamically via an ajax call). I know that I can use the live method to run the function. But what to eventuse in live method? I mean, what will even be called up when a new unit is dynamically created?

+5
source share
2 answers

You can use the mutation event DOMNodeInserted, but keep in mind that they are outdated and not supported in all browsers.

A better solution would be to write a custom event, for example:

$('#container').bind('MyAddEvent', function(){
    alert('Was added');
});

If you want the event to also apply to new elements, use on:

$('#container').on('MyAddEvent', '{selector}' ,function(){
    alert('Was added');
});

<div> ( ajax-), trigger:

...
success: function(result){
    $('#container').append(result)
    ...
    ...
    $('#container').trigger('MyAddEvent');
} 
  • , live , on - .

div, DOM x divs:

function checkForChanges()
{
    var newDivs = $('#container div').filter(function(){
            return !$(this).data('old')
        });

    ... //Do what you want with those divs      

    newDivs.data('old', true); // mark the div as old.

    setTimeout(checkForChanges, 1000); // Check the DOM again within a second.
}

$(checkForChanges);
+6

DOM demos DOM4 ( Webkit, ). . DOMNodeInserted , , . , Webkit.

+2

All Articles