When all you’ve got is a hammer…

Here’s a real life issue web developers have to deal with. Let’s say there’s an element on the page that needs to change color when you put your mouse over it. There are dozens of ways to accomplish this in JavaScript (or whatever JavaScript framework you’re using), but what’s the “best” way to do it?

If you eat, sleep, and breathe JavaScript, you’ve probably already thought of quite a few. In pure JavaScript, you could use this:

<html>
  <head>
    <style>
      #demo {
        color: blue;
      }
    </style>
  </head>
  <body>
    <span id="demo">Put your mouse over this</span>
    <script>
      document.getElementById("demo").onmouseover = function() {hoverIn()};
      document.getElementById("demo").onmouseout = function() {hoverOut()};

      function hoverIn() {
        document.getElementById("demo").style.color = "red";
      }

      function hoverOut() {
        document.getElementById("demo").style.color = "blue";
      }
    </script>
  </body>
</html>

Live demo

So that’s two event handlers (the “onmouseover” and “onmouseout” bits) and two JavaScript functions (the hoverIn and hoverOut functions). And if you’re into doing everything in JavaScript, this is probably the cleanest way to do it. But did you notice the <style> tags at the top?

If you’re so used to doing things in JavaScript that the above struck you as the best way to accomplish this, you may be forgetting about CSS. CSS pseudoclasses allow you to accomplish the same thing with no JavaScript at all, in a much simpler manner.

<html>
  <head>
    <style>
      #demo {
        color: blue;
      }
      #demo:hover {
        color: red;
      }
    </style>
  </head>
  <body>
    <span id="demo">Put your mouse over this</span>
    <script>
      //Nothing necessary here!
    </script>
  </body>
</html>

Live demo

We’ve gone from two functions and two event handlers to no JavaScript whatsoever, replaced with one simple, lightweight CSS pseudoclass declaration! That’s doggone fantastic!

I'm so excited!
I’m so excited!

The lesson here is that JavaScript, while supremely flexible and frankly awesome, is not the only tool in the toolbox. Almost everything having to do with the look and feel of elements on your web page can be handled without using JavaScript at all, which will result in cleaner, smoother code and takes you some of the way towards the separation-of-concerns ideal. Your JavaScript can focus on things like data exchange and element functions, rather than on such paltry concerns as the look and feel of those elements.