seedy
seedy

Reputation: 91

JQuery Animate Opacity On then Off While Animating Position

Having some trouble fading in and then fading out while animating position, all within the same duration. I would prefer to use opacity but fadeIn/fadeOut works. Thanks. Heres a JSFiddle

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

function runIt() {
    $('#ball').css({
        opacity: '0'
    }).animate({
        opacity: '1',
        left: '355'
    }, 2000).animate({
        opacity: '0'
    }, function () {
        $('#ball').removeAttr('style');
        runIt();
    });
}

JSFiddle

Upvotes: 0

Views: 516

Answers (2)

adeneo
adeneo

Reputation: 318182

To perform multiple animations simultaneously you have to call dequeue()

function runIt() {
    $('#ball').css({
        opacity : 0,
        left : 0
    }).animate({
        left: '355px'
    }, 2000).animate({
        opacity: 1
    },1000, function() {
        $(this).animate({
            opacity: 0
        },1000, runIt);
    }).dequeue()
}

FIDDLE

Upvotes: 1

Rayan Bouajram
Rayan Bouajram

Reputation: 743

Here's an example of a continuous interval with constant variables that you can adjust.

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

function runIt() {
    var WIDTH = 350,
        DURATION = 1000;

    $('#ball')
    .css({ opacity: '0', left: '0' })
    .animate({ opacity: '1', left: WIDTH/2 }, DURATION/2, 'linear')
    .animate({ opacity: '0', left: WIDTH }, DURATION/2, 'linear', runIt);
}

Fiddle: http://jsfiddle.net/2vT6M/6/

EDIT: cleaned up the code a bit.

Upvotes: 2

Related Questions