Shape up your coding style: separating CSS from JavaScript.

When starting to learn JavaScript and moving from developing static to dynamic sites, the power of being able to juggle DOM elements makes you feel like you’ve reached a whole new level of web development (and you have). If you want an element to look different after any event or at any point in time, you just restyle it using JavaScript. Here’s an example of how to do it, so we’re all on the same page.

But surely you’ve guessed, there is a pitfall about this. With the first sites you build this might work great. But you eventually run into a situation where you a) go back to your own code after a long time to make a change, or b) work as part of a team on more complex projects.

And then it happens. Your task is to change the ‘background-color’ of <body> to black. You open the CSS file, find ‘body’ in there, and change the background color to ‘#000000’. You reload the page to double check everything’s working and…what? It’s still white!!!? You reload three more times, clear your browser cache, try it in another browser, but it is still friggin white. After a few minutes you are starting to realize that the browser is displaying correctly, the color is changed to white via JavaScript at runtime.

So now the big search through JavaScript files starts to find where the heck that color is assigned to the element and why. This is especially fun if you’re close to a launch deadline and have to go through code you haven’t written. Alright, enough sarcasm, let’s get to how to do it better.

Define style states and save them in classes.

The solution to take all potential confusion and sweat out of this is to strictly separate JavaScript from CSS and let the former only deal with functionality and the latter with styling. This is done by adding a new class for an element into your style sheet whenever there is a need for a style change.

In your script, you only have to switch classes.

All styles for the relevant element are now in one place. When the task is to change black to dark blue, you only go into your CSS file and update the hex code. Even if you delete the class in the stylesheet to eliminate all black backgrounds, nothing will break. Sure, the class will still be assigned to your element through JavaScript (better delete that too if you’re trying to squeeze every bit out of performance), but it doesn’t alter the element anymore.

Never assign styles via JavaScript. Always assign classes. This way your code has a more clear structure, is more robust, and it is easier to grasp what visual states an element can assume.

 


Don't miss out on posts that help you become a better web developer. Get new articles delivered straight to your inbox.

You will get an email every 2-3 weeks. No spam.