Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering an event when an element is created

I wanna call a function on creation of new divisions in the DOM (i.e. created dynamically thru ajax call) .I know I can use live method for triggering the function. But what event should I use in the live method? I mean which even would be triggered when a new division is dynamically created?

like image 555
Rahul Avatar asked Mar 11 '12 13:03

Rahul


People also ask

What triggers an event?

What Is a Triggering Event? A triggering event is a tangible or intangible barrier or occurrence which, once breached or met, causes another event to occur. Triggering events include job loss, retirement, or death, and are typical for many types of contracts.

Which of the following event is triggered when an element in an HTML form?

The onfocus will be triggered when an element is in focus in HTML. The DOM onfocus event occurs at the time when an element is in focus.

What triggers JavaScript events?

onchange: It is triggered when an HTML element changes. onclick: It is triggered when an HTML element is clicked. onmouseover: It is triggered when the mouse is moved over a HTML element. onmouseout: It is triggered when the mouse is moved out of a HTML element.


2 Answers

You can use the DOMNodeInserted mutation event, but be aware that they are deprecated and not supported in all browsers.

Better solution would be to write a custom event like:

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

If you want the event to be applied to new elements as well, use on:

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

And when you add new <div> (after ajax requests), Trigger that event with trigger:

...
success: function(result){
    $('#container').append(result)
    ...
    ...
    $('#container').trigger('MyAddEvent');
} 
  • Note that live is deprecated, on is the new guy.

If you don't control the new divs insertion , you can inspect the DOM on each x time for new 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);
like image 135
gdoron is supporting Monica Avatar answered Oct 07 '22 12:10

gdoron is supporting Monica


Detect DOM changes with Mutation Observers demos DOM4 Mutation Observers (Webkit only, at the moment). So for now, you're quite screwed. DOMNodeInserted is not available in every browser, and where it is available, it is awful slow. Mutation Observers are much faster, but currently only available in Webkit.

like image 37
rodneyrehm Avatar answered Oct 07 '22 14:10

rodneyrehm