Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an HTML element repaint within a Javascript loop?

I have some Javascript which "animates" a colour change on an HTML element, as follows:

var element = document.getElementById("someid");
while (i < 255) {
    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';
    i++;
    slowMeDown(); // This function runs for a few ms to slow the process down
}

As you can see, this changes the color from black to white going through 255 shades of grey in between. I would like to make it visibly "fade" so that the user can see the text gradually disappear.

However, the browser (Chrome and IE - not tested on Firefox yet) only refreshes at the end of the function, so the color simply changes from black to white. Does anyone know how to make the browser repaint during the loop so that I can see the text fade?

like image 412
Leigh Caldwell Avatar asked Dec 09 '22 21:12

Leigh Caldwell


1 Answers

function changeColor()
{
    changeColorIncremental(0);
}

function changeColorIncremental(i)
{
    var element = document.getElementById("someid");

    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';

    if (i < 255) {
        // Note the 50 millisecond wait below.  Decrease this to speed up
        // the transition, and increase it to slow it down.
        setTimeout('changeColorIncremental(' + (i + 1) + ')', 50);
    }
}
like image 184
Sean Bright Avatar answered Feb 16 '23 01:02

Sean Bright