4

Today I encountered a problem when a rogue z-index property caused problems. Ok, it happens, but the problem was finding the place where it was declared. Browser shows inline style, but in markup it's empty, searching solution wide for z-index: 1001 also gave nothing.

Finally I found it in some JavaScript

        $("#header").css({
          //other props
          "z-index": "1001"
        });

This gave me some ideas about how it should be done, but I'm not sure.

The Question:

Is it better to change CSS from JavaScript prop by prop or make multiple CSS classes and change elements class from JS?

I am inclined to use multiple classes, but another option is welcomed.

Albzi
  • 15,431
  • 6
  • 46
  • 63
berzinsu
  • 915
  • 7
  • 12
  • 1
    For my money, I'd prefer to do it in classes rather than inline JS. When you're modifying styles, you go to the CSS. You don't want to dig through tons of JS rules to find that one "line-height" rule that's messing up your whole page. – aaron-bond Apr 02 '14 at 11:28
  • Maintainability: Multiple classes. Fast development: Inline in JS. – aurbano Apr 02 '14 at 11:30
  • 1
    According to Nicholas Zakas it's best practice to avoid coding style attributes in your JS. Instead use predefined classes and just change the className property with JS. Zakas is talking about it in this lecture: http://youtu.be/mHtdZgou0qU?t=35m12s – Nillervision Apr 02 '14 at 12:57

1 Answers1

7

I would advise just using the addClass and removeClass methods in jQuery. This way your JavaScript can be responsible for controlling behavior and your CSS remains responsible for the styling.

e.g. in your css:

.some-class {
    z-index:1001;
}

in your JavaScript:

$("#header").addClass('some-class');
//or 
$("#header").removeClass('some-class');
Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120