Bill Dybas

Building the Blog: Day 5

Today, we’ll finish the extravaganza by augmenting the site’s CSS with JavaScript.

While I do like the lavender I’ve chosen as the site’s primary color, I want the blog to stay interesting each time you visit. Therefore, we’re going to use JavaScript to change the primary color each time you visit. Each time will be a tiny surprise.

<script src="//code.jquery.com/jquery-3.1.1.slim.min.js"></script>

We’re going to use jQuery for its CSS selector-like interface in targeting elements. I’ve chosen the slim build to keep page loading times faster than if using jQuery’s entire build since we’re only using it to target elements and not do things like making AJAX calls.

Many people today are moving away from jQuery for more advanced technologies like React, Vue, and Angular, citing that jQuery becomes too hard to manage in large codebases and too tied to your HTML structure. I can agree with them that eventually it becomes hard to reason about what’s going on, how event handlers are hooked up, and whether changing some HTML will break your JavaScript (you have frontend tests, right? 😉), and from my own experience, when using jQuery on a Single-page App, remembering what part of the DOM needs to be visible or hidden becomes a complex task in and of itself.

Though I do think jQuery is a useful tool for small projects like this blog where the development experience can be more pleasurable by not having to work with the raw JavaScript Web APIs. And I don’t anticipate the codebase to grow significantly, so maintainability is not an issue here.

Enough of my babbling for now. Let’s write some code.

var colors = [
  'lavender',
  'cornflowerblue',
  'coral',
  'mediumseagreen',
  'indianred',
  'tomato',
  'gold',
  'slategray',
  'darkmagenta',
  'crimson',
  'darkorange',
  'darkslateblue',
  'turquoise'
];

We define an array of colors I’ve determined to look nice on the blog. I’ve chosen the word form of colors instead of hex values simply for convenience and readability.

var c = colors[Math.floor(Math.random() * colors.length)];

We’ll choose a random item from the array. Math.random() will do here; we won’t need guaranteed equal probability from a Fisher–Yates shuffle.

$('main, nav').css('border-color', c);
$('main').css('box-shadow', '10px 10px 0px ' + c);
$('nav').css('box-shadow', '5px 5px 0px ' + c);
$('a, .title').css('color', c);

And then we’ll select all the elements which should be colored and set them to this new color. Note on the box-shadow selector we have to also include the size - there’s no way currently to just change the color.

With just four lines, we’ve progressively enhanced the site, but not taken away the core experience if you happen to have JavaScript turned off.

And with that, our extravaganza comes to a close. I’ll put up a summary post with screenshots of the enhancements made each day for you Internet visitors who missed out but want to relive the experience.