Fernando Tiberti
Fernando Tiberti

Reputation: 1322

How to apply a function as soon as an element appears in jQuery?

I know in jQuery that there's the function live() to suscribe to events as soon as an element appears. I just want to do something to an element as soon as it appears. I tried suscribing the elements to the "load" event but it doesn't work. How do you go about that?

Upvotes: 0

Views: 203

Answers (4)

Lee
Lee

Reputation: 13542

You can listen to DOMNodeInserted. I know that works in Webkit and Firefox - I don't know about IE though.

It would look something like this:

$('body').bind('DOMNodeInserted', function(evt) {
    var addedElement = evt.target;
    // do whatever with `addedElement`...
})

Upvotes: 0

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

If you control the code which creates and appends elements, you could trigger a custom event and handle it in a handler later.

Example

$('#add').click(function() {
    $('#container').append($('<div>Hello! I am a new div</div>')).trigger('div-added');
});

$('#container').bind('div-added', function() {
    alert('A div has been added');
});

Upvotes: 1

Moin Zaman
Moin Zaman

Reputation: 25455

Use .delegate() http://api.jquery.com/delegate instead of .live()

For your specific case consider livequery http://docs.jquery.com/Plugins/livequery

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148624

you can't use load to all elements . only : Img Body Iframe.

and you can't listen via live to the load event of elements other the ones i mentioned.

what you can do - is when you add them to the Page - Then you know when its happened and then you can call your func.

Upvotes: 1

Related Questions