Doge
Doge

Reputation: 387

Window.width() for browser size?

I have the following JQuery function:

<script>
    $(document).ready(function(){
        var current_width = $(window).width();
        if(current_width => 1920){
            $("#body").css({    
                -moz-transform: 'scale(1, 1)', 
                zoom: '1',  
                zoom: '100%' 
            });
        }
        else if(1366 < current_width < 1920){
            $("#body").css({    
                -moz-transform: 'scale(0.85, 0.85)',
                zoom: '0.85', 
                zoom: '85%', 
            });
        }
       else if(current_width <= 1366){
            $("#body").css({    
                -moz-transform: 'scale(0.7, 0.7)',
                zoom: '0.7', 
                zoom: '70%' 
            });
       }

    });
</script>

I use a Chrome window resize extension to test different screen sizes, but when using the window.width JQuery function, despite the browser being resized, it's still detecting my native 1920px width. Is there something wrong with my code or I do really need to test different screen sizes using another devices when using the window.width() function?

Thank you

Upvotes: 0

Views: 223

Answers (1)

Tushar
Tushar

Reputation: 87203

Wrap your code in resize event handler. See the changes highlighted in the code below.

$(window).on('load resize rotate', function() {
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    var current_width = $(window).width();
    if (current_width >= 1920) {
        //            ^^

        $("#body").css({
            '-moz-transform': 'scale(1, 1)',
            // zoom: '1', Don't need
            zoom: '100%'
        });
    } else if (current_width > 1366 && current_width < 1920) {
        //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        $("#body").css({
            '-moz-transform': 'scale(0.85, 0.85)',
            // zoom: '0.85', // Not needed
            zoom: '85%',
        });
    } else if (current_width <= 1366) {
        $("#body").css({
            '-moz-transform': 'scale(0.7, 0.7)',
            // zoom: '0.7', // Not needed
            zoom: '70%'
        });
    }
});

Upvotes: 1

Related Questions