Search code examples
javascriptjqueryhtmlcssmedia-queries

Sticky javascript when physically dragging to resize browser window


I have a function(s) that expand a drop down list when the browser is size n.

Size n is determined by css media queries and works as expected.

However when I physically drag the width of the browser window out, the .click function remains bound to the element even though a media query indicates that a css hover effect takes place when the browser is size n + 1.

A refresh at any point produces the desired behavior but of course I don't want to require a refresh.

   var section_4 = "#main-menu > li:nth-child(4) > a";
   var sub_section_4 = "#main-menu > li:nth-child(4) > ul";

    $( section_4 ).click(function() {
        $( sub_section_4 ).slideToggle(300);        
        return false;
    });

how can I apply this function only on a given size and not have the .click follow to the inline list ? thanks


Solution

  • You could use jquery .width() and .resize() like this:

    var section_4 = "#main-menu > li:nth-child(4) > a";
    var sub_section_4 = "#main-menu > li:nth-child(4) > ul";
    
    var docWidth = (window).width();
    $(document).resize(function(){
        docWidth = (window).width();    // Refresh value on resize
    });
    
    $( section_4 ).click(function() {
        if( docWidth < [integer] ){        // set integrer the same as your @media.
            $( sub_section_4 ).slideToggle(300);
            return false;
        }
    });