1

Now Solved, thanks

I have see a lot of near answers to my problem with resize(), here is my code:

'larger()' is a layout function that I want to call when screen width regardless of device orientation is >= 501, 'smaller()' is a function that i want to call when the screen width is < 501.

My problem I have is that I don't want these functions to be called when the window.height changes. Note that in my page I am using an accordion in mobile view and if I expand an accordion panel, it adds height to the page, even though the browser window hasn't been re-sized. jQuery sees this as a window.resize.

$(window).resize(function(e) {
    var winWidth = $(window).width();
    if (winWidth >= 501){
       larger();
    }
    if (winWidth < 501){
       smaller();
    }
});

any answers appreciated, and let me know if I need to clarify anything.

I am using jquery-1.11.0.min.js with jquery-ui-1.10.3.custom.min.js

Thanks

0

2 Answers 2

3

How about storing a reference to the previous width and if the width has changed on resize then call your functions - otherwise skip it. Like So:

// If you don't want it to change the first time
// then set this value on document load to get initial window width
var prevWinWidth = 0;

$(window).resize(function(e) {
    var winWidth = $(window).width();

    if(winWidth != prevWinWidth) {
        if (winWidth >= 501){
            larger();
        }
        if (winWidth < 501){
            smaller();
        }
        prevWinWidth = winWidth;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

hi the problem is that I don't want the nested functions to get called on height change, when page height changes. I guess what I need is a way to detect the physical browser re-size, not the window
But they won't get called if there is a height change without a width change. If you never want the functions to be called if the height has changed then use a variable to track also the height change and only call your functions when the width has changed but the height hasn't
0

Create a global variable that keeps track of the last known width of the window. Only if the width is changing, evaluate the width to call the appropriate function.

var lastWidth = 0;
$(window).resize(function (e) {
    var winWidth = $(window).width();
    if (lastWidth !== winWidth) {
        winWidth >= 501 ? larger() : smaller();
        lastWidth = winWidth;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.