ToggleClass not adding Jquery Delay?

306 views Asked by At

I am trying to add a delay to the toggleclass 'slidein' however it doesn't seem to be adding to it.

here is my fiddle

and here is my code;

 $(function () {
        $(".expand").on("click", function () {
            $(this).next().slideToggle();

                if ($(this).next().css("display", "block")) {



                    $(this).next().children('#slidinghold').delay(5000).toggleClass('slidein');


            }

            $expand = $(this).find(">:first-child");


            if ($expand.text() == "\u25B6") {
                $expand.text("\u25BC");


            } else {
                $expand.text("\u25B6");
            }
        });

    });
3

There are 3 answers

2
NightOwlPrgmr On BEST ANSWER

Try this:

$(this).next().children('#slidinghold').delay(5000).queue(function(){
    $(this).toggleClass("slidein").dequeue();
});

Fiddle

2
Anthony Carbon On

use setTimeout instead of delay. Sample :

$(".expand").on("click", function () {

    $(".expand").next().children('#slidinghold').removeClass('active-expand');

    $(this).next().children('#slidinghold').addClass('active-expand');

    setTimeout(function () {
        $('.active-expand').next().children('#slidinghold').toggleClass('slidein');
    }, 500);
});

demo https://jsfiddle.net/anthonypagaycarbon/v1geqa8e/

0
n00dl3 On

as said by jQuery's doc

.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases

So you can use window.setTimeout to achieve this:

$(function() {
    function toggleClassDelay(element,class,delay) {
        window.setTimeout(function() {
            element.toggleClass(class)
        },delay);
    }
    $(".expand").on("click", function() {
        var el;
        $(this).next().slideToggle();

        if ($(this).next().css("display", "block")) {
            el = $(this).next().children('#slidinghold');
            toggleClassDelay(el,"slidein",5000)
        }
        $expand = $(this).find(">:first-child");
        if ($expand.text() == "\u25B6") {
            $expand.text("\u25BC");
        } else {
            $expand.text("\u25B6");
        }
    });

});