0

I need to fire an jquery action when a div is appended.

Something like:

if ($('div#myDiv').is_appended()) {
console.log('the div has been appended');
}

Is this possible?

Why do I need this

This question is related to this question where I have I modal div which is loaded after the jquery library, then I can't target the element in it.

Now I'm trying to do something when the modal div is load, not sure if I get it done though,

Community
  • 1
  • 1
Jaso2970
  • 149
  • 2
  • 7
  • 12
  • 1
    Why do you need to do it in the first place? Maybe there’s a better way. – Ry- Feb 26 '13 at 15:08
  • No, events are fired for user actions. Since this is being added by code, what you should do is tie your function to whatever's doing the adding. – Blazemonger Feb 26 '13 at 15:09
  • I think [this](http://stackoverflow.com/questions/4979738/fire-jquery-event-on-div-change) should answer your question. – ncksllvn Feb 26 '13 at 15:09
  • @minitech look at the bottom of my question (just edited) – Jaso2970 Feb 26 '13 at 15:13

1 Answers1

2

Not in a cross-browser way, not yet. There is a draft specification for mutation observers which would allow it (more on this MDN page), but it's only implemented in recent WebKit-based browsers and Firefox.

There's almost always a better approach available, such as triggering the action from the code appending the div. In the worst case (and I mean "worst"), you could use polling every (say) 100ms and detect the new div. But again, there's almost always a better way.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875