Last Updated: February 25, 2016
·
738
· jisaacks

jquery.added2dom

Sometimes you need to run some code when an element is added to the DOM.

Here is my contrived example without added2dom:

$div = $('<div>Hello World</div>')
$div.text $div.height()

# later on
$("body").append $div
# output <div>0</div>

Now with added2dom:

$div = $('<div>Hello World</div>')
$div.added2dom ->
  $(this).text $div.height()

# later on
$("body").append $div
# output <div>18</div>

In the real world with javascript templates in common usage in frameworks like backbone.js, you may need to do something in your view that requires being in the DOM to work. This is a way to ensure that a piece of code doesn't get run until its in the DOM, since most likely the view is not adding itself to the DOM and unaware when that happens.

In your render method you might do something like this:

render: =>
  @$el.html @template()
  @$el.added2dom -> @doSomething()
  @

Get it here:

added2dom

If you like it: endorse