Search code examples
javascriptjquerymobileresponsive-designmedia-queries

Trigger an accordian menu with Media Queries?


I'm wondering if it would be possible to trigger a jQuery accordion menu, at a specific viewport stated in CSS3 Media Queries.

EG; For mobile devices, below 450px width viewport > the normal menu disappears > and a jQuery accordian menu appears in it's place.

How could I get this done? Is there a way I could set a conditional for viewports as doable for IE, that could hide that menu, and pull in my new jQuery accordion one?


Solution

  • If I understand your question correctly, you could simply have the menu and the accordion on two separate divs, and change their display CSS property to either block or none depending on the viewport width, like this:

    @media only screen and (max-width : 450px) {
        .accordion { display: block; }
        .normalmenu { display: none; }
    }
    @media only screen and (min-width : 450px) {
        .accordion { display: none; }
        .normalmenu { display: block; }
    }
    

    If your accordion and menu have the same HTML structure, you could listen for the window resize event and load the accordion; of course, you should also check it on the initial load:

    $(window).resize(function() {
        checkWidthAndLoadAccordion();
    });
    
    $(document).ready(function() {
      checkWidthAndLoadAccordion();
    });
    
    function checkWidthAndLoadAccordion() {
        if($(window).width() < 450) {
            // load your accordion
        }
    }
    

    Hope it helps.