M. David Green

Existence is a byproduct of semantics

How to Coordinate CSS With Javascript

Javascript is used to change the content of an HTML page, and apply various CSS styles, dynamically in response to user action and other factors. When writing HTML and CSS, consider how you might use Javascript to manipulate the pages. It is important to provide the Javascript programmers with useful semantic targets which they can populate with new information, or style by applying different CSS. For example, if there is a word in your document that you know will be generated in Javacscript, create a to contain it, and allow the Javascript programmer to assign it an appropriate id.

If the Javascript programmer needs to alter the HTML, move HTML blocks from one place to another using Javascript commands such as the JQuery commands .after() or .before(), or dynamically generate CSS styles not defined in our CSS pages, our application will be more brittle and harder to manipulate in the future.

Knowing how the page will work before coding the HTML skeleton is critical. For example, it allows us to create the spans which the Javascript programmers will fill with information, and the divs which will be shown, hidden, and otherwise manipulated. With AJAX, a single page may change radically over its lifetime on a user’s screen. Examine the page carefully to see which elements will change, and which ones will stay the same. We are less likely to break the layout of a page if we replace the content of a single defined header div across the lifetime of the page than we are if we hide that header div and then show another in the same location.

The JQuery Javascript library allows programmers to target HTML elements in a page using the same CSS definitions that define the style of the elements. While that is convenient, it is generally more flexible to separate the functionality of the Javascript from the presentation of the CSS. That way, if things change in the style, they are less likely to compromise the program logic. Javascript is also much more efficient about parsing a large document for id’s than for classes. Therefore, I recommend using unique id’s for targeting Javascript to an element, and using classes and inheritance to apply styles to an element.