SpencerDub
SpencerDub

Reputation: 425

Why doesn't my jQuery respond to window resize?

I'm using jQuery to add some make some elements on a page transition (via the jQuery Transit plugin) when hovered upon. Since I'm trying to design responsively, I want these transitions to only happen when the browser is a certain size or larger.

I've written the following code as an attempt to do this:

$(document).ready(function(){
    var $window = $(window);
    var $logo = $('.logo');
    
    function checkWidth() {
        windowsize = $window.width();
    }
    
    checkWidth();
    
    $(window).resize(checkWidth);
    
    if (windowsize >= 768) {
        $logo.hoverIntent(
            function(){
                $logo.transition({
                    perspective: '600px',
                    rotateY: '-10deg'
                });
            },
            function(){
                $logo.transition({
                    perspective: '600px',
                    rotateY: '0deg'
                });
            }
        );
    }

});

If I load the page in a large browser, it works as expected--the hover effect is active. If I resize the browser, making it smaller (past the breakpoint) and refresh, then it works--the hover effect is disabled. But if I resize the window without refreshing in between, then the effect doesn't respond--it either remains disabled (if resizing from a small to a large screen) or active (if resizing from large to small).

It's a minor quirk, to be sure, but I can't exactly figure out why it's happening. As far as I can tell, when the window resizes, it should be updating the windowsize variable, which should be checked in the if statement. What am I overlooking that makes this not the case?

Upvotes: 1

Views: 845

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

All checkWidth currently does is assign a value to windowsize. You need to move the code that actually reads windowsize into checkWidth.

$(document).ready(function(){
    var $window = $(window);
    var $logo = $('.logo');

    function checkWidth() {
        windowsize = $window.width();

        if (windowsize >= 768) {
            $logo.hoverIntent(
                function(){
                    $logo.transition({
                        perspective: '600px',
                        rotateY: '-10deg'
                    });
                },
                function(){
                    $logo.transition({
                        perspective: '600px',
                        rotateY: '0deg'
                    });
                }
            );
        }
    }

    // can trigger the resize handler instead of
    // explicitly calling checkWidth()
    $(window).resize(checkWidth).resize();
});

Upvotes: 2

Related Questions