Search code examples
javascriptjquerydelaytoggleclass

jQuery delay between each toggleclass


I have made a (rather complicated) solution where I have 4 menu items pop in/out from the side and I make that happen by toggling a class.

$('.menuitem').toggleClass('show');

It works great but the client now wants it to "slide out". I figured that I can make him happy if I can create a delay between each toggle, but I cant find a good way to do it. In practice I want each menu item to toggleClass but with a delay of maybe 250ms before next toggleClass.

Edited - Apparently the delay function wont work with toggle, only with animations.


Solution

  • Consider this following code:

    $('.menuitem').each(function(i) { 
        var elm=$(this);
        setTimeout(function() { 
            elm.toggleClass('show');
        }, i * 250); 
    });
    

    See it in action, in this demo i have hiding diving one by one and delay is 1000 ms.