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?
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.
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.
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.
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');
}
live
is deprecated, on
is the new guy.If you don't control the new div
s 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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With