0

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?

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I already implemented the answer of Sacho but your answer works as well! thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.