javascriptjqueryclassfadeto

How can I stop jquery from running a script once for each class member


I have the following code:

function fadeIn()
    {
    $(".home_photo").fadeTo(1000, 1.0 ).delay(5 * 1000);
    fadeOut();
    }

function doSwap()
    {
    console.log('Swap');
    ... There is some Ajax Code here that swaps the image in the divs ...
    fadeIn();
    }

function fadeOut()
    {
    $(".home_photo").fadeTo(1000, 0.01, doSwap );
    }

$(document).ready(function(){
    fadeOut();
});

Here is the HTML that goes with it:

<body>
<div id="photowrapper">
    <div class="home_photo" id="img1"></div>
    <div class="home_photo" id="img2"></div>
    <div class="home_photo" id="img3"></div>
    <div class="home_photo" id="img4"></div>
</div>
</body>

The jQuery script runs one time for each member of the class "home_photo". The problem is that the doSwap function runs 4 times for each swap cycle (fadeOut, doSwap, fadeIn). What do I need to do so that the script will only run once per swap instead of once for each class member?


Solution

  • If you want doSwap() to run after the fadeTo() has completed you could use a jQuery deferred object to control the process:

    $.when(function() {
    
        var deferred = $.Deferred();
    
        $(".home_photo").fadeTo(1000, 0.01, function(){
            deferred.resolve();
        });
    
        return deferred;
    
    }).then(function(){
    
        doSwap();
    
    });