javascriptandroidjquerygoogle-chromeandroid-virtual-keyboard

Call jquery function only when window width gets resized


I have a function responsive that changes behaviour of certain elements on my website, including hiding popups etc. I call it in 2 cases:

$(document).ready(responsive);
$(window).resize(responsive);

The problem occurs on android chrome, as the virtual keyboard actually changes the height of the screen, and triggers responsive function, which closes my popups (some of them have text fields, making it impossible to type).

How can I prevent this from happening? I read somewhere a good point that android virtual keyboard only changes height of the screen, not a width, so I assume it would be a good idea to compare width before and after resize. So I created this function to compare the widths before and after and run resize() if width is different, but it doesn't work as expected, and console logs show different document widths even though I only changed the height of the screen (using chrome developer tools).

Any idea what went wrong or how can I prevent function responsive being launched on height change?

function resizeWidth() {
    var existingWidth = $(document).width();

    $(window).resize(function() {
        var newWidth = $(document).width();
        if (existingWidth != newWidth) {
            $(window).resize(responsive);
            console.log(existingWidth);
            console.log(newWidth);
        };
    });
};

$(window).resize(resizeWidth);

Solution

  • Firstly you are attaching a handler to the resize event multiple times. One on load, then another every time the resize happens and resizeWidth is called. You should remove the handler within that function. Also, I guess you just want to call the responsive() function, not attach yet another resize handler when the width changes.

    The main issue you have is that the scope of existingWidth is not low enough for it to be seen over multiple events. You could make it global, although that is generally considered bad practice. Instead you could use a data attribute, like this:

    function resizeWidth() {
        var existingWidth = $(document).data('resize-width');
        var newWidth = $(document).width();
        if (existingWidth != newWidth) {
             responsive();
             $(document).data('resize-width', newWidth);
        };
    };
    
    $(window).resize(resizeWidth);