Search code examples
javascriptjqueryhtmlcssmaterialize

Detecting materialize framework side-nav width using jquery


I am trying to detect the materialize side-nav element if its open, my goal is to run a function when detected that side-nav is open the HTML tag below is from the materilize.css documentation which side-nav will only appear if screen is in mobile size, everythings work perfectly i just need to detect if size-nav is open or not.

 <nav>
    <div class="nav-wrapper">
      <a href="#!" class="brand-logo">Logo</a>
      <a href="#" data-activates="mobile-demo" class="button-collapse"><i class="material-icons">menu</i></a>
      <ul class="right hide-on-med-and-down">
        <li><a href="sass.html">Sass</a></li>
        <li><a href="badges.html">Components</a></li>
        <li><a href="collapsible.html">Javascript</a></li>
        <li><a href="mobile.html">Mobile</a></li>
      </ul>
      <ul class="side-nav" id="mobile-demo">
        <li><a href="sass.html">Sass</a></li>
        <li><a href="badges.html">Components</a></li>
        <li><a href="collapsible.html">Javascript</a></li>
        <li><a href="mobile.html">Mobile</a></li>
      </ul>
    </div>
  </nav>

My jquery is below, for now i am trying a console.log(), my goal for now when i click the side nav menu and opens a console.log will fire up.

<script>


  $(document).ready(function(){

      $(".button-collapse").sideNav();



     if ($('.side-nav').length > 0) {

        console.log('side nav is open');

      } else {

         console.log('side nav is close');
      }

  });


</script>

But cannot get it to work, any suggestion would be great thanks in advance!


Solution

  • as provided in the documentation , there are some events that you can detect the openning and closing of the sidenav , just add it to the options as following

    $('.button-collapse').sideNav({
          onOpen: function(el) { console.log('side nav is open');}, // A function to be called when sideNav is opened
          onClose: function(el) { console.log('side nav is close');}, // A function to be called when sideNav is closed
        }
      );