jQuery Standards (4) – Page Style and Layout Changes

Synopsis

Avoid making changes to individual CSS styles using the jQuery API functions.

Use CSS Classes intead.

Description

Avoid using direct CSS style changes (using .css() ), and inbuilt style functions .length(), .width(), etc.

Instead, declare the styles in a class within a CSS StyleSheet file (not inline within an HTML file!), and use .addClass(), .removeClass() or .toggleClass() upon your selecteded object(s).

For example, avoid this type of declaration:

    $("#MyTR").css({
       "background-color":"gray"
    });

Use instead:

    $("#MyTR").addClass("HighlightRow");

    /*In CSS File:*/
    .HighlightRow
    {
       background-color:gray;
    }

This promotes correct separation of content and style.

Embedding style changes in JavaScript/jQuery has the following implications when it comes to rebranding or changing a site’s theme:

  • It is less likely that a consistent approach has been adopted with regard to styling making the task harder.
  • A bigger and more complex  impact analysis required to identify files that require changed.
  • More files require changed.
  • More files = more testing. As we will be changing JavaScript code, we will have to retest more than we otherwise would have.

A discussion on the merits of Behavioral Separation is outside the scope of this article. It may seem a little draconian to advise against using .css() and other style-change functions, but is essential when attempting to achieve this goal.

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining

One thought on “jQuery Standards (4) – Page Style and Layout Changes

  1. Pingback: jQuery Coding Standards and Best Practice « James Wiseman

Leave a Reply