Home > Enterprise >  jQuery: Using const variable and setTimeout to trigger a menu animation
jQuery: Using const variable and setTimeout to trigger a menu animation

Time:08-27

I'm using jQuery, and I 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 pseudo code to help you guys understand my issue because I tend to waffle on a lot.

PSEUDO 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