Search code examples
jquerydomclonevisibility

Why does jQuery add "visibility:hidden" to a div and all its children when I clone it?


So, I have a template div like this:

<div class='container'>
  <div class='mybox invisible' id='template'>
     <span>some stuff</span>
     <div>test</div>
  </div>
</div>

So I want to clone it to create items based on it.

new_item = $('#template').clone()
$(new_item).removeClass('invisible').attr('id','some_crap').appendTo('.container')

It works beautifully. BUT, if I run this code ON DOCUMENT READY (to pre-load some items), then everything gets an inline visibility: hidden added (the .mybox div, and ALL its children).

My workaround for now is, instead of pre-loading my items on dom ready, waiting 1 second.

setTimeout (->
    preloadOffices()
), 1000

(yea, coffeescript)

That seems to do the trick, but I'm wondering if there are more elegant solutions.


Solution

  • .clone() does not add arbitrary style values to the objects it clones. As such, I think there are only two possible explanations here:

    1. The objects are actually visibility: hidden at document.ready() time and some code is actually making your other object visible later. .clone() just makes copies of the objects as they are. It doesn't add arbitrary style values to them.

    2. Some other code is making your cloned object visibility: hidden after you clone it.

    If you showed us your actual page, we could likely figure out what was really happening.

    You can debug this yourself by stepping through your code and watching what state things are in as the code runs. Or, you can insert some console.log statements that examine what state things are in.