0

I have two divs, .box-1 and .box-2.

I want to set the height of both to be equal to whichever has the greater height.

Can anyone tell me why this code doesn't work?

var $box1Height = $('.box-1').height();
var $box2Height = $('.box-2').height();

if ($box2Height > $box1Height) {
    ($box1Height).height($box2Height)
} else {
    ($box2Height).height($box1Height)
}
Soviut
  • 88,194
  • 49
  • 192
  • 260
am624
  • 13
  • 2

2 Answers2

2

The elements that you want to update are $(".box-1") and $(".box-2"). Instead of update them, you took theirs height value, and tried to update their height value's height value (something like that: $(".box-1").height().height(new_value);, which obviously doesn't exist. The compare was good, but the update wasn't for the right elements.

Instead of taking $('.box-1').height();, you can take only the element $('.box-1') and work with it.

Like this:

var box1 = $('.box-1');
var box2 = $('.box-2');

Now that we have the element itself, let's work with it's attributes. To get the height of the element- use:

box1.height();

To set new value to this height property, use:

box1.height(new_value);

Put it all together:

var box1 = $('.box-1');
var box2 = $('.box-2');
if (box1.height() > box2.height()) {
    box1.height(box2.height())
} else {
    box2.height(box1.height())
}
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
1

You can get the largest height of the two by using Math.max(), removing the need for an if statement. Then just set both box heights to the result of .max()

var maxHeight = Math.max(box1.height(), box2.height())
box1.height(maxHeight)
box2.height(maxHeight)

Below is a working example

$(function() {
  // cache the box selectors
  var box1 = $('.box1')
  var box2 = $('.box2')
  
  // determine which box is taller
  var maxHeight = Math.max(box1.height(), box2.height())
  
  // apply the tallest height to both
  box1.height(maxHeight)
  box2.height(maxHeight)
})
.box1 {
  display: inline-block;
  height: 100px;
  width: 50px;
  background: cornflowerblue;
}

.box2 {
  display: inline-block;
  height: 50px;
  width: 50px;
  background: rebeccapurple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">box1</div>
<div class="box2">box2</div>
Soviut
  • 88,194
  • 49
  • 192
  • 260