Search code examples
javascriptjqueryfunctionif-statementwindow-resize

jQuery Resize - Initializing Function (If parameter issues)


The code below just executes a function when the viewport width (a var) is over a set width.

var viewportWidth = $(window).width();

function refit__slider__height(){
    var fitted__height  = $('#promobanner__wrap').height() - 150;

    $('#promobanner--slider').height( fitted__height );
}

$(document).ready(function() {
    if ( viewportWidth > 767 ){
        refit__slider__height();
    }
});

// for the window resize
$(window).resize(function() {
    if ( viewportWidth > 767 ){
        refit__slider__height();
    }
});

However I have noticed that when the if statement is below 767 then gets resized above 767 the JS condition is not caught, a page refresh has to occur for the if condition to match.

Has anyone come across this? Or no of a solution?


Solution

  • You need to reinitialize viewportwidth again in resize event like,

    var viewportWidth = $(window).width();
    $(document).ready(function() {
        if ( viewportWidth > 767 ){
            refit__slider__height();
        }
        $(window).resize(function() {
            viewportWidth = $(this).width();// re-init width on resizing window
            if ( viewportWidth > 767 ){
                refit__slider__height();
            }
        });
    });