g3rriascn g3rriascn - 3 months ago 23
jQuery Question

jQuery animation timing

I have here a function and what I want to happen is to display the div first before it smoothly changes it's width.. Unfortunately what happen is that the width already changes once it appears

CSS:

#frame12{
opacity:0;
filter:alpha(opacity=0);
width:100;
}


jQuery:

function animatestamp(){
jQuery("div#frame12").css({'opacity':'1','filter':'alpha(opacity=100)'}).animate({
width:'451px'
},animatestamp);
}

PSL PSL
Answer

Use animate on div's opacity first and then on its complete callback animate the width.

function animatestamp() {
    jQuery("#frame12").animate({ //animate the opacity first
        'opacity': 1,
        'filter': 'alpha(opacity=100)'
    }, 2000, function () { //Once it is completely visible start animating the width
        $(this).animate({
            'width': '451px',
        }, 1000);
    });
}
animatestamp();

Fiddle

For recursive you can try this:

var $frame = jQuery("#frame12");

function getWidthConfig(elem) { //get the width animate object based on current elem width
    return {
        'width': elem.width() > 450 ? '100px': '451px' 
    }
}

function getOpacityConfig(elem) {//get the opacity animate object based on current elem opacity
    var opac = +elem.css('opacity');

    return {
        'opacity': !opac ? 1 : 0,
        'filter': !opac ? 'alpha(opacity=100)' : 'alpha(opacity=0)'
    }
}

function animatestamp() {
    $frame.animate(getOpacityConfig($frame), 2000, function () {
        $frame.animate(getWidthConfig($frame), 1000, animatestampReverse);
    });
}

function animatestampReverse() {
    $frame.delay(2000).animate(getWidthConfig($frame), 1000, function () {
        $frame.animate(getOpacityConfig($frame), 2000, animatestamp)
    });

}
animatestamp();

Fiddle