punkrockbuddyholly
punkrockbuddyholly

Reputation: 9794

Perform function when window.width is resized but not the height

I'm developing a responsive website and I have some tabs that change from tabs to an accordion on small screens. Here is how I am doing it at the moment:

var myGlobalVariable = {};

$(window).resize(function(e) {
    duringResize();
    myGlobalVariable.windowWidth = window.innerWidth;
});

function widthHasChanged() {
    return window.innerWidth !== myGlobalVariable.windowWidth;
}

function duringResize() {
    if(widthHasChanged()) {
        if(Modernizr.mq('all and (min-width:1000px)')) {
            /* Do stuff for tabs */
        } else {
            /* Do stuff for accordion */
        }
    }
}

I'm not happy about this because I'm having to use a global variable to store the last width of the browser window in order to check wether the width has changed.

The reason I have to do this is because on mobiles when the tabs are in accordion mode clicking on one actually makes the document taller to accommodate the tab content. For some reason this is classed as a resize even though the 'window' is still the same size on a mobile. This meant that my tab/accordion code was being called even when the width hadn't changed and this was messing things up.

Is there something I'm missing or is this the only way to achieve this? jQuery and vanilla javascript solutions are welcome.

Upvotes: 0

Views: 82

Answers (1)

SteveP
SteveP

Reputation: 19093

There is no specific event to bind to for window width change. Your solution looks fine to me.

The only other way I could think of was to do a regular check on $(window).width inside a timer. I think on balance, the single global variable is preferable :)

Upvotes: 1

Related Questions