codybuell
codybuell

Reputation: 338

Javascript to Measure Multiple Div Heights

I'm trying to build out an accordion menu with jQuery but am running into jumpy animations. The jumpiness is caused by not setting a height for the div. My problem is that each div is going to have a different height based on the contents; so the question is, how would I use javascript to look at each div with the class 'submenu', measure it's height, and set it.

Here is what I have so far:

$('.submenu').each(function() {
  var divh = $(this).height();
  $(this).css('height', divh + 'px');
});

What I'm running into is that it only seems to measure one .submenu div and sets all of them to that height. Thoughts? Thanks in advance!

Upvotes: 0

Views: 1832

Answers (2)

codybuell
codybuell

Reputation: 338

Believe I found the problem. I had the above script in a $(document).ready() function which would only have loaded, and subsequently measured, the DOM. Moved it to a $(window).load() function which let it see the content and then measure the height. As a point of clarification the .submenu class divs are the accordion divs.

$(window).load(function(){
  $('.submenu').each(function() {
    var divh = $(this).height();
    $(this).css('height', divh + 'px');
  });

  $('.submenu').hide();
});

Upvotes: 1

GregM
GregM

Reputation: 2654

Suppose too look like this :

$('.submenu').each(function() {
  var divh = $(this).height();
  $('.divClass').css('height',  $('.divClass').height() + divh + 'px');
});

You need to always add the current div height in your for to your accordion div

Upvotes: 0

Related Questions