I have lots of div elements where I need to recalculate their heights. The divs are inside another div with id="content".
I'm using jQuery like this:
$("#content div").css("height", "*=" + Math.random());
There are about about 1000 divs that are recalculated like that. It takes some time to do this and I understand it is because the layout is recalculated once for each element. It only takes a few seconds, but it is way to much.
I got a tips earlier about using document fragments which is regular JavaScript. I would love to be able to use jQuery to do this.
Is there any way, using jQuery, to separate this divs and manipulate them outside the active DOM before writing them back, so that the layout isn't recalculated until I'm finished with the manipulation?
Try using detach
Something like the following:
HTML
<div id="content" >
<div class="test" style="height:100px;">
</div>
<div class="test" style="height:100px;">
</div>
<div class="test" style="height:100px;">
</div>
<div class="test" style="height:100px;">
</div>
<div class="test" style="height:100px;">
</div>
jQuery
var el = $('.test').detach();
el.each(function(index){
var height = $(this).attr('style').substring($(this).attr('style').indexOf('height:')+7,$(this).attr('style').indexOf('px'));
$(this).attr('style','height:'+height*Math.random()+'px');
});
$('#content').append(el);
I had trouble manipulating the height on detached elements.. I did find one way to do it though if you have the height in the style attribute you can pull the information from there and manipulate it.
Here is an example, hopefully it will be helpful to you.
http://jsfiddle.net/4Sb8T/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With