jQuery Behave like Media Queries when Resizing Bro

2019-06-14 08:38发布

问题:

I've been struggling with this for a while. Basically I have a div (#memberrevealwrapper) that is a specific height unless the viewport is less than 790px in width, then it is another height. (It's a responsive web design)

Now, #memberrevealwrapper is animated using jQuery to make it function like a pull tab that comes from the top of the browser upon click and then click again and it rolls back up.

Here is my jQuery:

<script>
    $(document).ready(function() {
        $('#memberloginrevealwrapper').animate({ marginTop: '-75px'}, 200);
        $('#memberloginlink a').toggle(
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
            },
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '-75px'}, 500);
            }
        );
    });

    $(document).ready(function(){
        var pageWidth = $(window).width();  

        if ( pageWidth <= 790 ) {

            $('#memberloginrevealwrapper').animate({ marginTop: '-147px' }, 200);
            $('#memberloginlink a').toggle(
                function(){
                    $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
                },
                function(){
                    $('#memberloginrevealwrapper').animate({ marginTop: '-147px'}, 500);
                }
            );

        }; 
    });

</script>

This works great until you resize the browser. When you resize the browser, it doesn't find the new height and to readjust the height.

Here is the site in action: clients.januarycreative.com/PES. I am referring to the "Member Login" tab at the top of the page.

Anyone know how I can get jQuery to refresh when the browser is resized? I've tried everything I know how, and have managed everything from cutting off the page to making the page bounce like a basketball many times in a row.

Thank you in advance!

回答1:

You need to re-run the code over again as the browser resizes. What you have up there just runs the code one on page load. You need a loop (technically an event that fires over and over again as the page resizes).

Here you go:

function updateSize() {
    var pageWidth = $(window).width();  

    if ( pageWidth <= 790 ) {
        $('#memberloginrevealwrapper').animate({ marginTop: '-147px' }, 200);
        $('#memberloginlink a').toggle(
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '0' }, 500);
            },
            function(){
                $('#memberloginrevealwrapper').animate({ marginTop: '-147px'}, 500);
            }
        );
    }
}

$(window).resize(updateSize);