refresh or trigger javascript on window resize

500 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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);
1
On

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
    });
});