1

Assume I have the following function:

function createDiv(){
  var div = $("<div>");
  //here specify a callback to be triggered after the div has been attached to the DOM.
  return div;
}

The div element will be attached to the DOM body, and assume I have no ideas on when it will really become part of the DOM. But eventually the other parts of the app will be responsible to attach the element to the active DOM. With this assumption in the createDiv function, I would like to have a callback to do the further processes that is only sensible after the element is in the DOM.

Is this type of callback achievable?

Kata
  • 685
  • 1
  • 9
  • 22

1 Answers1

1

any dynamically created element is attached to DOM only after some other method is called to attach it in DOMtree like append(),html(),text() and so on..

here, in your function, you are just creating an element and returning it.. so this is not actually attached to DOM... the created div should be appended to DOM first and then you can specify callback to be triggered after it is appeneded..

example,

function createDiv(){
 var div = $("<div>");

return div;
}

$(function(){
   var DivElement=createDiv();
   $('body').append(DivElement); //so now you are sure the element is in the DOM.
});
bipen
  • 36,319
  • 9
  • 49
  • 62
  • Thanks, the question is assuming I don't know when the element will be attached to DOM, so that is why I would like to know if that kind of *callback* is achievable. – Kata Mar 27 '13 at 09:38
  • This is actually a subsequent question resulted from this answer http://stackoverflow.com/questions/15628734/typeset-mathjax-before-element-attaching-to-dom/15637559?noredirect=1#15637559 – Kata Mar 27 '13 at 09:55
  • hmmm... even the answer is poiting out to the same answer as mine.. you need to attached created element to the DOM first to use MathJax ...you create an element `div` so there have to be something that is attaching this create element to the DOM... there is no way it will be attached to the DOM as soon as it is created... `assume I have no ideas on when it will really become part of the DOM` .. here assuming is useless cause it is sure the created element is not attached to DOM at all....until and unless you use mothod i mentioned to attach the created div – bipen Mar 27 '13 at 10:01
  • I have updated the question -- the other part of the app will be responsible for doing the DOM attaching action. This question is more about the callback design pattern in DOM I think. – Kata Mar 27 '13 at 10:08
  • `But eventually the other parts of the app will be responsible to attach the element to the active DOM.` so you need to call mathjax where you are attacing the element (other parts of app) eventually..... there is no other way as far as i know... – bipen Mar 27 '13 at 10:13