Home > Net >  Jquey: Using const variable and setTimeout to trigger a menu animation
Jquey: Using const variable and setTimeout to trigger a menu animation

Time:08-27

I'm using JQuery and am trying to get my dropdown menu to work by toggling the "active" class that I have in my CSS but I've been having an issue with changing the timeout on one of the elements. Here is the psuedo code to help you guys understand my issue because I tend to waffle on a lot.

PSUEDO CODE

When button is clicked
Toggle active class on navbar and dropdown menu
If dropdown has active class
Set a timeout of .3s and toggle active class on 'content-wrapper' If dropdown doesn't have active class
Remove timeout and toggle active class on 'content-wrapper'

CODE

//load animation for dropdown menu
$("document").ready(function(){
 const navbar = $(".mobile-navbar");
 const contentWrapper = $(".content-wrapper");
 const menuBtn = $(".menu-button-container");
 const dropdown = $(".nav-dropdown-menu");

 menuBtn.click(function(){
   navbar.toggleClass("active");
   dropdown.toggleClass("active");
   // if dropdown menu has the active class
   // set a timout of .3 seconds for the content
   // wrapper, else, remove timout
   if(dropdown).hasClass("active"){
     setTimeout(function(){
       contentwrapper.toggleClass("active");
     }, 300) else {
     setTimeout(function(){
      contentWrapper.toggleClass("active");
     }, 0);
    }
   }
 });
 });

CodePudding user response:

let's try to help you with this issue.

I'm not sure why you need a timeout here, but in your description of the problem you are telling us that you remove the timeout. But you don't use the clearTimeout() function.

Here is what I would try:

//load animation for dropdown menu
$("document").ready(function(){
 const $navbar = $(".mobile-navbar");
 const $contentWrapper = $(".content-wrapper");
 const $menuBtn = $(".menu-button-container");
 const $dropdown = $(".nav-dropdown-menu");
 let myTimeout;

 $menuBtn.click(function(){
   $navbar.toggleClass("active");
   $dropdown.toggleClass("active");
   // if dropdown menu has the active class
   // set a timout of .3 seconds for the content
   // wrapper, else, remove timeout

   if ( $dropdown.hasClass("active") ) {
     myTimeout = setTimeout(function(){
       $contentwrapper.toggleClass("active");
     }, 300);
   }
   else {
      clearTimeout(myTimeout);
      $contentWrapper.toggleClass("active");
   }
 });
});

I also set the naming to your const by adding a $ before the name. A var, let or const with a $ before is considered as a jQuery object. That's a good practice you should keep :)

Hope I could help.

  • Related