test
test

Reputation: 2466

jQuery add a class after fadeOut completly done

Here is the code:

<style>
#box1, #box2, .container { position: absolute; top: 0px;z-index:10; height: 50px; }
#box1 { background-color: #ff0000; width: 100px; left: 200px; }
.container { width: 640px; overflow: hidden; height: 50px; background-color:#000; color:#FFF; }
</style>


<div class="container">
<div id="box1"></div>
</div>

<script>
var animateMe = function(targetElement, speed){
    var position = $(targetElement).position();
    var positionA = $(targetElement).position();
    if(positionA.left = '400px'){
        $(targetElement).fadeIn(1000).css({left:'200px'});
    };
    //animate
    $(targetElement).animate(
        {
        'left': '400px'
        },
        {
        duration: speed,
        complete: function(){
            animateMe(this, speed);
            }
        }
    ).fadeOut(1000);
};

$('.container').hover(function(){
    animateMe($('#box1'), 2000);
},
function(){
    $('#box1').stop();
});
</script>

What I want is when hover:

  1. fadesIn

  2. animates to right

  3. FadesOut (when fadeOut done resets left position)

  4. then again repeats to number 1.

But my code is it resets postition then fadesOut, fadesIn ...

Upvotes: 1

Views: 449

Answers (2)

Jasper
Jasper

Reputation: 75993

You can use callback functions to delay the execution of some code until other code finishes running:

$(targetElement).animate({ 'left' : '400px' }, {
    duration : speed,
    complete : function () {
        var that = this;
        $(that).fadeOut(1000, function () {
            animateMe(that, speed);
        });
    }
});

Also if (positionA.left = '400px) will always return true since you are not using the conditional operator, the code should be: if (positionA.left == '400px) (or you could use === to match type and value).

Upvotes: 0

arunes
arunes

Reputation: 3524

I create jsfiddle at http://jsfiddle.net/SdS68/

var animateMe = function(targetElement, speed){
    $(targetElement).css({ left: '200px' }).fadeIn(1000, function() {
        $(targetElement).animate({
            'left': '400px'
        }, {
            duration: speed,
            complete: function() {
                $(this).fadeOut(1000, function() {
                    animateMe(this, speed);
                })
            }
        }).fadeOut(1000);
    });
};

Upvotes: 1

Related Questions