开发者

Detect window resize and perform function with jquery

开发者 https://www.devze.com 2023-03-26 23:34 出处:网络
How can I make it so that e开发者_运维技巧ach time when user changes the window size, the page perform a function?The following function should do what you need, it works on all browsers (with the sin

How can I make it so that e开发者_运维技巧ach time when user changes the window size, the page perform a function?


The following function should do what you need, it works on all browsers (with the single exception of not firing when Safari is NOT maximized and resolution changes)

It fires upon window re-sizing as well as resolution change and also has a delay to avoid multiple calls while the user is re-sizing the window.

    var resizeTimer;

    //Event to handle resizing
    $(window).resize(function () 
    {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(Resized, 100);
    });

    //Actual Resizing Event
    function Resized() 
    {
        //Your function goes here
    };

Testing jsFiddle


In regards to this article: https://developer.mozilla.org/en-US/docs/DOM/window.onresize

window.onresize = resize;

function resize()
{
    alert('window size changed');
}

window.resize makes it quite simple.


My proposition. First HTML & CSS.

HTML

<div id="wrapper">
    <div id="div1">
        #div1 content
    </div>
    <div id="div2">
        #div2 content
    </div>
</div>

CSS

div {
    color: white;
    margin: 20px;
    padding: 5px 18px;
    font: 700 16px/200% sans-serif;
}
#div1 {
    background-color: #d00;
}
#div2 {
    background-color: #27d;
}

Now the jQuery:

On document ready only (https://jsfiddle.net/sz7aeo9j/)

<script>
    $(document).ready(function () {
        var divone = $('#div1')[0].outerHTML
        var divtwo = $('#div2')[0].outerHTML
        $('#div2,#div1').remove();
        if ($(window).width() < 640) {
            $('#div1').remove();
            $('#wrapper').html(divtwo);
        }
        if ($(window).width() > 640) {
            $('#div2').remove();
            $('#wrapper').html(divone);
        }
    });
</script>

On window resizing (https://jsfiddle.net/sz7aeo9j/1/)

<script>
    $(document).ready(function () {
        var divone = $('#div1')[0].outerHTML
        var divtwo = $('#div2')[0].outerHTML
        $('#div1').remove();
        $(window).resize(function () {
            if ($(window).width() < 640) {
                $('#div1').remove();
                $('#wrapper').html(divtwo);
            }
            if ($(window).width() > 640) {
                $('#div2').remove();
                $('#wrapper').html(divone);
            }
        });
    });
</script>


you can register an event onresize on the window : a function is called when window size changed

https://developer.mozilla.org/en/DOM/window.onresize


Use screen.width and screen.height to determine the width and height of the screen.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号