user2436715
user2436715

Reputation: 3

Resize div height with jquery

I'm trying to resize div heights dynamically based on browzersize, and based on this script (found here ):

$(document).ready(function() {
    setHeight('.col');
});

var maxHeight = 0;
function setHeight(column) {
    //Get all the element with class = col
    column = $(column);
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();;
        }
    });
    //Set the height
    column.height(maxHeight);
}

script works great, I just need it to also run when a browser window is resized for responsive purposes.

It would make sense to do something like this:

$(window).resize(function() {
setHeight('.col');
});

and then also reset the "maxHeight" somehow...

No bueno - any ideas?

Upvotes: 0

Views: 10198

Answers (2)

user1823761
user1823761

Reputation:

Working jsFiddle Demo

For thie first time that setHeight function runned, the height of elements initialized. And for the second time, always the same height will be returned. You must remove the height from them before your loop:

column.css('height', 'auto');

And, also your var maxHeight = 0; must be in your function itself:

$(document).ready(function() {
    setHeight('.col');
});


function setHeight(column) {
    var maxHeight = 0;
    //Get all the element with class = col
    column = $(column);
    column.css('height', 'auto');
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });
    //Set the height
    column.height(maxHeight);
}


$(window).resize(function() {
    setHeight('.col');
});

Upvotes: 3

imbecile
imbecile

Reputation: 468

edit: here you go. it works for me :)

$(document).ready(function() {
   setHeight('.col');

   /*if this is not placed before it is to be called, 
     the browser won't recognize it, 
     which is why i preferably register these 
     event functions in ready()*/
   window.onresize=function(){setHeight('.col');}; 
});

function setHeight(column) {
   var maxHeight = 0;   
   //Get all the element with class = col
   column = $(column);
   //Loop all the column
   column.each(function() {       
   //Store the highest value
     if($(this).height() > maxHeight) {
      maxHeight = $(this).height() ;
     }
  });
   //Set the height
   column.height(maxHeight);
   console.log(column +" " + maxHeight);
}

misread the q: make the maxHeight variable local to the function. It's value will then be reset whenever you exit the function.

Upvotes: 1

Related Questions