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
Not directly but there are some good suggestions on minimising the impact of reflows here:
http://dev.opera.com/articles/view/efficient-javascript/?page=3
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( posElem.style.cssText ) != 'undefined' ) {
posElem.style.cssText = newStyle; // Use += to preserve existing styles
} else {
posElem.setAttribute('style',newStyle);
}
You could set the element's visibility to 'hidden', then apply the styles and then make it visible again.
You could put all the styles in a CSS class
.foo { background:#000; color:#fff; ... }
and then assign it to the className property
// javascript
var your_node = document.getElementById('node_id');
your_node.className = 'foo'
That should trigger only one repaint/reflow
use:
document.getElementById('elemnt_ID').setAttribute('style','color:white; margin:5px;');
If you were using jQuery, it has a .css function that allows you to add multiple style at once:
$('element').css({'color':'red', 'border':'#555 solid thin'});