Xah Lee
Xah Lee

Reputation: 17555

Google Chrome JavaScript Fade: style.opacity and setTimeout

i have a JavaScript script that fade a element.

the gist is just this:

function fade() {
    if (cat.style.opacity > 0) {
        // decrease opacity slightly
        cat.style.opacity -= 0.1;

        // call fade again in a fraction of a second
        setTimeout( fade, 60 );
    } else { 
        cat.style.visibility = "hidden";
    }
}

( full code here http://xahlee.info/js/js_fadeout.html , JavaScript code here: http://xahlee.info/js/js_fadeout.js )

In Google Chrome, it doesn't fade completely. Seems the loop stuck and the style.opacity never reaches 0.

On StackOverflow, it seems a Google Chrome bug from a post a year ago, but never really confirmed.

Seems strange, as this would be a major bug. Anyone know why it doesn't work in Google Chrome?

Upvotes: 1

Views: 1622

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

This appears to be a precision issue. You can get around it pretty easily by using .toFixed to the precision that you need.

cat.style.opacity = (cat.style.opacity - 0.1).toFixed(2);

http://jsfiddle.net/GgPqc/

Upvotes: 4

Related Questions