HTML5 Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 150 posts at DZone. You can read more from them at their website. View Full User Profile

Quick Tip – Change CSS Classes and Not Element Styles

04.02.2013
| 1631 views |
  • submit to reddit

A few days ago I wrote a quick tip to ensure only one reflow when you need to manipulate the Document Object Model (DOM). Continuing that post, here is another JavaScript mistake I’m seeing from time to time and a way to go around it.

The Scenario

You need to change some element’s style as a response to some event. Here is a simple function that contains the problem:

function changeElementStyle(element) {
    element.style.color = '#fff';
    element.style.backgroundColor = '#000';
    element.style.width = "100px";
}

If you read my previous post, you know that every single DOM manipulation including style changes can trigger a reflow. In the previous code we have three potential reflows.

Suggested Solution

A way to solve the previous problem is using CSS classes instead of manipulating the element’s style. First, you will have to add a new class in your CSS file. Here is the previous style changes as a CSS class:

.changedstyle {
    color: #fff;
    background-color: #000;
    width: 100px;
}

Now change the previous function to the following function:

function changeElementStyle(element) {
    element.className = 'changedstyle';
}

Now we will have only one optional reflow instead of three and that is better.

Summary

When you are manipulating your DOM you should remember the Browser reflow process even if it is only simple style change. You can’t control when reflows occur but you can minimize their impact on your app performance.



Published at DZone with permission of Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)