Ahmed-Anas
Ahmed-Anas

Reputation: 5619

jquery to make 2 column height equal only works when alert()

hey guys hope you can help me out,

I am having a weird problem. I am working on a web page that has two floating divs (among many other things). To make the floating divs of equal height, I added the following code

$(document).ready(function(){

   alert($('#body-left').height());
    if($('#body-left').height()>$('#sidebar').height()){
     $('#sidebar').height($('#body-left').height());

    }
    else{

    $('#body-left').height($('#sidebar').height());

    }

});

see the line "alert($('#body-left').height());", when I remove that line, it stops working :/. I.e :

this is what happens when I dont add the alert() line: enter image description here

and this is what happens when I do add the alert line

enter image description here

any ideas why this is happening? :/


sorry for the late reply guys, but I got it working using

if($('#body-left').height()>$('#sidebar').height()){
    setTimeout(function(){
     $('#sidebar').height($('#body-left').height());
    },100);

}
else{
    setTimeout(function(){
    $('#body-left').height($('#sidebar').height());
    },100);
}

any ideas?

Upvotes: 2

Views: 201

Answers (2)

Blazemonger
Blazemonger

Reputation: 92953

Using this question as a basis, you can quickly take the max height of any number of elements. If you gave them all the class equalheight, you could do this:

$(document).ready(function() {
    var maxheight = $.map($('.equalheight'), function(val, i) {
        return $(val).height();
    }).max();
    $('.equalheight').height(maxheight);
});

Array.prototype.max = function() {
    return Math.max.apply(Math, this);
};

http://jsfiddle.net/mblase75/NR9TZ/

Upvotes: 1

Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14784

If you want equal heights...try this plugin:

$.fn.setMinHeight = function(setCount) {
  for(var i = 0; i < this.length; i+=setCount) {
    var curSet = this.slice(i, i+setCount), 
        height = 0;
    curSet.each(function() { height = Math.max(height, $(this).height()); })
          .css('height', height);
  }
  return this;
};

Copy and paste the above code into a JS file and link to it. Then call it like so...

$(".theItems").setMinHeight(2); // Pass in number of items to include.

Hope this helps.

Michael.

Upvotes: 1

Related Questions