Update CSS styles? (Redraw page)

This is one weird problem that I am facing. I am developing an application using Cordova (Phonegap) and the styles of many elements depend on class I set to body

. For example,

.gray .background{
    background: gray;
}
.gray .title{
    color: white;
}

      

When i do

document.body.classList.add("gray");

      

all styles on the page should change to the "new" style. However, one device I've tested is acting strangely. The style was not updated, however through some class registration via JS I know the class has been added. For some reason, the style remains the same. It doesn't always happen, sometimes it does, sometimes it behaves right.

So, is there a way to manually "trigger" a style update?

+3


source to share


1 answer


Not a very pretty solution, but on some android devices I solved similar problems only with a timeout, for example:

setTimeout(function () {

    document.body.classList.add("gray");
}, 0);

      

Timeout "0" usually works, but in some rare cases even later execution is required.



The above code will wait for the execution queue to finish and the class change. Especially on some devices with poor performance, some changes do not have enough time to render at runtime JS (possibly due to a bug in the HTML renderer).

But it's also important to keep in mind that your code may have other parts that could lead to this behavior.

It is also possible to force the browser to redraw using the method described in Force Redraw. If this still does not solve the problem, the redraw itself can be delayed using SetTimeout.

+2


source







All Articles