Search code examples
jquerytoggleclass

jquery toggleClass over the course of 3.5ms


Why is this function not working properly? Everything works as it should, with the exception of the toggleClass toggling over the course of 3.5ms. It toggles correctly, but no animation occurs.

This code below is a rough illustration of a more complex navigation, but the idea is the same.

$('ul#menu-main-menu li:nth-child(2) a').click(function() {
      $('ul#menu-main-menu').toggleClass('nav-border', 350);
  });
ul#menu-main-menu {
  padding: 20px;
  border-radius: 20px;
  border: 1px solid #ddd;
}

li {
  display: inline-block;
  margin: 0 10px 0 0;
  cursor: pointer;
}

.nav-border {
  border-radius: 20px 20px 0 0 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-rc.1/jquery-ui.min.js"></script>
<ul id='menu-main-menu'>
  <li>
    <a> First</a>
  </li>
  <li> 
    <a> Second</a>
  </li>
  <li> 
    <a> Third</a>
  </li>
</ul>

Thank you all.


Solution

  • You can do it by using css transition property.

    transition :border-radius 350ms;
    

    Full code:

    $('ul#menu-main-menu li:nth-child(2) a').click(function() {
          $('ul#menu-main-menu').toggleClass('nav-border', 350);
      });
    ul#menu-main-menu {
      padding: 20px;
      border-radius: 20px;
      border: 1px solid #ddd;
      transition :border-radius 350ms;
    }
    
    li {
      display: inline-block;
      margin: 0 10px 0 0;
      cursor: pointer;
    }
    
    .nav-border {
      border-radius: 20px 20px 0 0 !important;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id='menu-main-menu'>
      <li>
        <a> First</a>
      </li>
      <li> 
        <a> Second</a>
      </li>
      <li> 
        <a> Third</a>
      </li>
    </ul>