Reputation: 730
I am using this javascript to make two child div's the same height in their parent div:
$(function(){
var leftHeight = $('.leftblock').height();
var rightHeight = $('.rightblock').height();
if (leftHeight > rightHeight){ $('.rightblock').css('height', leftHeight); }
else{ $('.leftblock').css('height', rightHeight); }
});
When I resize the window one of the divs is getting a lot longer again but now the javascript doesn't work anymore. I placed the exact same script again in the window resize function and that solves the problem!
$(window).resize(function(){ // same script as above again });
My question; is there a cleaner way so I can just use the script once but refresh or trigger the script again on window resize?
Upvotes: 0
Views: 493
Reputation: 23816
You can declare function and call it whenever you want.
Try using function :
function check(){
var leftHeight = $('.leftblock').height();
var rightHeight = $('.rightblock').height();
if (leftHeight > rightHeight){
$('.rightblock').css('height', leftHeight);
} else {
$('.leftblock').css('height', rightHeight);
}
}
$(function(){
check();//calling function on window load
$(window).resize(function(){
check();//calling function on window resize
});
});
Upvotes: 1
Reputation: 2179
Sure, declare a function and use it in both handlers:
function resizeDivs() {
var leftHeight = $('.leftblock').height();
var rightHeight = $('.rightblock').height();
if (leftHeight > rightHeight){ $('.rightblock').css('height', leftHeight); }
else{ $('.leftblock').css('height', rightHeight); }
}
$(resizeDivs);
$(window).resize(resizeDivs);
Upvotes: 2