Coşku DEMİRHAN
Coşku DEMİRHAN

Reputation: 94

How can I detect a jquery Fade animation is in process or not?

Here is the code about jQuery fadeIn fadeOut

function timecheck(obj,options,inAction){
    var items = options.items;

    // check if anything needs to be done
    for (var i=0; i<items.length; i++) {
            if(items[i][0]> obj.get(0).currentTime) {
                $('#item_'+i).hide();
            }else if(items[i][0]<=obj.get(0).currentTime && items[i][1] >= obj.get(0).currentTime && !inAction['item_'+i]){
                console.log(inAction['item_'+i] = true);
                $('#item_'+i).fadeIn('normal',function(){ inAction['item_'+i] = false; console.log(inAction); });


            }else if(!inAction['item_'+i]){
                console.log(inAction['item_'+i] = true);
                $('#item_'+i).fadeOut('normal',function(){ inAction['item_'+i] = false; console.log(inAction); });

            }

    }

This code call by javascript every 40ms. my problem is callbacks try to set false incorrect inAction elements. How can i provide that?

Upvotes: 0

Views: 262

Answers (2)

alexbchr
alexbchr

Reputation: 613

You can use the jQuery animation queues. Simply pass a string representing the name of your animation queue to the animating functions (hide, fadeIn, fadeOut, ...). For example, use your hide function like :

$('#item_'+i).hide({queue: "queueName"});

Then simply retrieve the number of animations left in your animation queue using :

$('.#item_'+i).queue("queueName").length;

You can intermittently check the value of length using window.setInterval and then apply your logic when the length property reaches 0.

See jQuery documentation for details :

queue

animate (same thing for hide(), fadeIn() and fadeOut())

Upvotes: 1

kalley
kalley

Reputation: 18462

For loops continue increasing. You need a closure and since you're using jQuery already, here is an option:

function timecheck(obj, options, inAction) {
    var items = options.items;

    // check if anything needs to be done
    $.each(items, function(i) {

        if (items[i][0] > obj.get(0).currentTime) {
            $('#item_' + i).hide();
        } else if (items[i][0] <= obj.get(0).currentTime && items[i][1] >= obj.get(0).currentTime && !inAction['item_' + i]) {
            console.log(inAction['item_' + i] = true);
            $('#item_' + i).fadeIn('normal', function () {
                inAction['item_' + i] = false;
                console.log(inAction);
            });


        } else if (!inAction['item_' + i]) {
            console.log(inAction['item_' + i] = true);
            $('#item_' + i).fadeOut('normal', function () {
                inAction['item_' + i] = false;
                console.log(inAction);
            });

        }

    });
}

Otherwise, what is happening is that when the callback is called, it's already at the i already equals items.length

Upvotes: 1

Related Questions