Tower Tower - 1 year ago 72
Javascript Question

Is there a way to apply multiple CSS styles in a batch to avoid multiple reflows?

I know that altering element's style via JavaScript directly will cause a reflow. However, I was wondering if it is possible to alter multiple style values in a batch with only one reflow?

Answer Source

Not directly but there are some good suggestions on minimising the impact of reflows here:

In short, try something like this:

The second approach is to define a new style attribute for the element, instead of assigning styles one by one. Most often this is suited to dynamic changes such as animations, where the new styles cannot be known in advance. This is done using either the cssText property of the style object, or by using setAttribute. Internet Explorer does not allow the second version, and needs the first. Some older browsers, including Opera 8, need the second approach, and do not understand the first. So the easy way is to check if the first version is supported and use that, then fall back to the second if not.

var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
  'color: ' + newColor + ';' +
  'border: ' + newBorder + ';';
if( typeof( ) != 'undefined' ) { = newStyle; // Use += to preserve existing styles
} else {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download