Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh CSS styles? (Repaint page)

This is one weird issue that I encountered. I've been developing an app with Cordova (Phonegap), and many elements' styles depend on the class I set on body. For example,

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

When I do

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

all the styles on the page should change to the "new" style. However, there's one device that I tested on is acting strange. The style did not get updated, however through some logging of the class through JS I know that the class has been added. For some reason the style remains unchanged. This doesn't always happen, sometimes it does, sometimes it behaves correctly.

So, is there a way to manually "trigger" an update to the styles?

like image 960
Derek 朕會功夫 Avatar asked Apr 11 '26 10:04

Derek 朕會功夫


1 Answers

Not a pretty solution but on some Android devices I've solved similar problems only by a timeout like;

setTimeout(function () {

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

The timout of "0" generally works but in some rare cases even later execution is needed.

The above code will wait for all the execution queue to catch up and changes the class. Especially on some low performance devices some changes have not enough time to be rendered while JS is executing (possibly due to a bug in HTML renderer).

But it is also important to keep in mind that your code may have other parts that may result in this behaviour.

Also it is possible to force the browser to redraw using the method explained in Force Redraw If this still does not solve the issue, the redraw itself can be delayed using a SetTimeout.

like image 158
Ali Naci Erdem Avatar answered Apr 12 '26 23:04

Ali Naci Erdem