Haradzieniec
Haradzieniec

Reputation: 9340

jQuery: execute a function AFTER toggleClass was executed

I have

<script>
function myfunc(){
alert("show this alert in 5000ms after toggleClass executed")
//some code goes here
}

$(document).ready(function(){
    $('.mybtn').on('click',function(){
        $('#mydiv').toggleClass('newclass');
    });
 });
</script>

How to execute myfunc() in 5000ms after toggleClass was executed? Tried several ways but with no luck.

Thank you.

Upvotes: 1

Views: 2208

Answers (5)

user688074
user688074

Reputation:

I would do the $("#mydiv").toggleClass('newclass') in a separate event.

For instance <button class="mybtn" onmousedown="$('#mydiv').toggleClass('newclass')" onclick="myfunc();">Fast Toggle</button>

If you toggle onmousedown the page will render with the toggle before the click event fires.

Upvotes: 0

LoneWOLFs
LoneWOLFs

Reputation: 2306

Try this...

function myfunc(){
alert("show this alert in 5000ms after toggleClass executed");
//some code goes here
}

$(document).ready(function(){
    $('.mybtn').on('click',function(){
        $('#mydiv').toggleClass('newclass').delay(5000).queue(myfunc);        
    });
});

JSFIDDLE DEMO

Upvotes: 3

iJade
iJade

Reputation: 23801

You can have a callback function like this

$('#mydiv').toggleClass('newclass', 5000).promise().done(function(){alert("done")});

Here is a working demo

Upvotes: 0

Manoj
Manoj

Reputation: 1890

Use settimeout function

function myfunc() {
    alert("show this alert in 5000ms after toggleClass executed")
    //some code goes here
}

$(document).ready(function () {
    $('.mybtn').on('click', function () {
        $('#mydiv').toggleClass('newclass');
        setTimeout(myfunc, 5000)
    });
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

use setTimeout()

function myfunc() {
    alert("show this alert in 5000ms after toggleClass executed")
    //some code goes here
}

$(document).ready(function () {
    $('.mybtn').on('click', function () {
        $('#mydiv').toggleClass('newclass');
        setTimeout(myfunc, 5000)
    });
});

Upvotes: 7

Related Questions