Search code examples
jquerymedia-queriesmodernizr

tablet orientation change with jquery and modernizr


So I have a nav menu which changes style when viewing tablets in portrait or landscape. It collapses the last few menu items into another drop down menu. Yet the menu doesn't update upon orientation change, only doing so after a refresh.

Jquery Modernizr code:

if(Modernizr.mq('(max-device-width: 800px) and (orientation: portrait)')){
    // portrait stuff
        // unhides last few menu items
        $('#menu-primary-items > li:nth-last-child(-n+3)').css('display', 'block');

        // remove hide and first child class originally assigned to it from it's ul parent
        // then add the more list item to the end of the nav menu
        $('.moreItem').removeClass('hide first-child').appendTo('#menu-primary-items');

        // grab the last two items of the nav menu and insert into the more list item menu
        $('.topNavigation .toplevel').slice(-2).appendTo('.moreMenu');
    } 

Any suggestions??


Solution

  • So it appears that wrapping the function in a resize listener makes it work! Also seemed to work better when having an else statement. Just need to do further testing on other devices.

    Updated code:

    $(window).bind('resize', function(){
    
        if(Modernizr.mq('(max-device-width: 800px) and (orientation: portrait)')){
        // portrait stuff
            // unhides last few menu items
            $('#menu-primary-items > li:nth-last-child(-n+3)').css('display', 'block');
    
            // remove hide and first child class originally assigned to it from it's ul parent
            // then add the more list item to the end of the nav menu
            $('.moreItem').removeClass('hide first-child').appendTo('#menu-primary-items');
    
            // grab the last two items of the nav menu and insert into the more list item menu
            $('.topNavigation .toplevel').slice(-2).appendTo('.moreMenu');
        } else if(Modernizr.mq('(max-device-width: 1280px) and (max-device-height: 800px) and (orientation: landscape)') || Modernizr.mq('(max-device-width: 1024px) and (orientation: landscape)')){
    
            $('.moreMenu').children().appendTo('#menu-primary-items');
    
            $('.moreItem').addClass('hide first-child').appendTo('.moreItemHolder');
    
            $('#menu-primary-items > li:nth-last-child(-n+3)').css('display', 'block');
    
        }
    });