3

When resizing the browser, I have a simple function that checks the window ratio in order to affect layout, part of which is:

if ( jQ(window).width() > ($elemH*2) ) /* Target widest settings */ {
    $body.addClass('wide').removeClass('tall');
    $elemW = ($elemH*2);
    productWideSize();

The above works perfectly, with 0 issues (I've included it for purely for context). The problem seems to lie in productWideSize(), which is as follows:

function productWideSize(){
    $info = jQ('#productInfo');
    $infoH = jQ('#productInfo').outerHeight();
    $maxH = (jQ('#product-form').height()-120);
    if ( $infoH < $maxH ) /* Check if element height is LT available space */ {
        $info.removeClass('scroll').css({
            'margin-top' : '-' + $infoH/2 + 'px'
        })
    } else {
        $info.addClass('scroll').css({
            'margin-top' : '',
        })
    };
};

When carefully resizing the browser, it works pretty well; but if a sudden browser-size change is made, often the transition between the if/else sections doesn't fire. Tested in Chrome and Firefox.

Obviously the code "works" but it's not particularly robust. I'm still new to coding, and wonder if I'm employing some fundamentally bad practice. Any suggestions?

verism
  • 1,106
  • 1
  • 12
  • 35

1 Answers1

0

It appears as though the problem was caching the values before referencing them in the condition. Changing it to the following works:

function productWideSize(){
    $info = jQ('#productInfo');
    if ( jQ('#productInfo').outerHeight() < jQ('#product-form').height()-120 ) {
        $info.removeClass('scroll').css({
            'margin-top' : '-' + jQ('#productInfo').outerHeight()/2 + 'px'
        })
    } else {
        $info.addClass('scroll').css({
            'margin-top' : '',
        })
    }
};
verism
  • 1,106
  • 1
  • 12
  • 35