NLAnaconda
NLAnaconda

Reputation: 1595

Fastest way to get the height of a div

The situation

I've created an HTML "book" where every page is a div:

The divs have all absolute position's because they have to be on top of each other.

Now the height of the book has to be that of the highest page. So I've created an "heightkeeper" div which has "visibility:hidden" so the heightkeeper div is never visible but keeps the height of the book as height as the highest page.

So far so good, but now...

The problem

When the book is initialized I check with JavaScript the height of every page. I get the content of that page and add that to the heightkeeper.

$book.find("div.page").each(function () {
                        pageHeight = $(this).height();

                        if (highestPagePx < pageHeight) {
                            highestPagePx = pageHeight;
                            highestPageContent = $(this).html();
                        }
                    });

This works perfect in all the modern browsers but now I'm debugging IE8 and this takes a lot of time... In my virtual machine (which is not fast but old browsers are on old computers) it takes around 40 ms per page. With 10 pages that's almost half a second. With 3 books on a webpage it takes like 1.5 seconds. In my opinion to long.

Does anybody can come up with a creative solution?

I was thinking of how to set relative div's on top of each other so the whole heightkeeping stuff is unnecessary. But I can't figure out how to do that.

Upvotes: 0

Views: 152

Answers (2)

Artem Gorlachev
Artem Gorlachev

Reputation: 617

i think that this takes a lot of time:
highestPageContent = $(this).html();

better get the index of biggest page:
highestPageContentIndex = $(this).index();

and outside loop:
highestPageContent = $("div.page").eq(highestPageContentIndex).html();

Upvotes: 0

adeneo
adeneo

Reputation: 318252

Try less jQuery :

var pages   = $book.find("div.page").get(),
    highest = 0;

for (var i=0; i<pages.length; i++) {
    if ( pages[i].clientHeight > highest) highest = pages[i].clientHeight;
}

for (var i=0; i<pages.length; i++) {
    pages[i].style.height = highest;
}

Upvotes: 1

Related Questions