Search code examples
javascriptcssdecoupling

CSS and Javascript too tightly coupled (CSS is not just presentation but is used by UI and JS), how to improve this?


I think supposedly, an ideal way is that CSS only deals with presentation aspect of a document, and so CSS and Javascript are de-coupled and it is a very clean solution. We can change any CSS or any Javascript without breaking the other.

But what if we implement fancy UI, such as grayish words in a search box, and the word will disappear once the user clicks in the box, those type of behavior? In such cases, CSS and Javascript are very coupled and changing CSS will affect the Javascript some where, and it is hard to handle because in a project, there can be 5000 lines of CSS and 8000 lines of Javascript, and the need to hunt each other down and change them together can make it buggy and hard to maintain. Is there a better way or ways of doing it so that it is more clean?


Solution

  • In some ways it's better, and some worse, but you could add the CSS in your javascript. Many jquery plugins for instance create all CSS needed as part of the script, meaning that the whole lot is in one place.

    This is better because the CSS files and JS files are distinct, but it involves moving presentation into your JS layer.