3 ms·
There are a few problems with doing that, in my experience. First, from a theoretical point of view, Javascript is an functional language. That's ideal for ex
by IsaacSchlueter 18y ago
There are a few problems with doing that, in my experience.
First, from a theoretical point of view, Javascript is an functional language. That's ideal for expressing event-driven behavior. Not so great for expressing style information. It's the difference between saying, "When you walk in the room, look at the wall, and see that it is red" vs saying "The wall is red." Style information is best expressed in a declarative rule-based syntax.
Second, from a practical point of view, CSS and JS are loaded and run in different ways by the browser. CSS, being a declarative rule-based language, can be loaded up ahead of time, and applied to the DOM all in one go. Javascript must be parsed and evaluated, and respond to changes dynamically. Great for click events, not so great for specifying FAC and layout.
Third, from a maintainability point of view, even when it perhaps makes some sense to set styles dynamically in Javascript (ie, DHTML), it's usually better to have the JS modify a className and put the style rules in a CSS file. To the browser, it makes no difference. But to the next programmer dealing with your code, who's wondering where a particular style is coming from, it makes it a lot easier to fix bugs. This is the "don't put canned goods in the fridge" rule. Sure, it doesn't hurt the refrigerator or the can of soup, but you'll go a little crazy every time you look in the cupboard and can't find it.
That being said, the CSS/JS divide is far from conceptually or practically perfect. CSS already has a bunch of event-driven hooks (:active, :focus, :hover, etc.), and there are some cases where you simply must modify the HTMLElement::style object. But like everything else in a web page, there's a trade-off, and the rules of thumb are there for a reason. Know them well, so that you can know when and why it's appropriate to break them.