Better Typography with JavaScript

By Cory LaViska on June 3, 2019

Learn how to automatically improve your website's typography using a bit of JavaScript.

Letter stamps in a box

Keyboards don't come with smart quotes, ellipses, and em dash keys, so to produce elegant typography, the user has to press complicated keyboard combinations. This isn't very convenient, so here's a way you can get better typography automatically using JavaScript.

To do this, we'll be using an open source library called typogr.js, which is available under the MIT license. This library does a few things, including:

  • Wraps ampersands with <span class="amp"> so they can be styled
  • Converts straight quotes into smart curly quotes
  • Converts -- to en dash and --- to em dash
  • Converts ... into an ellipsis
  • Prevents widows by adding &nbsp; between the last two words

For a complete list of everything typogr.js does, refer to the readme.


Installation

First we need to link to the typogr.js script on all the pages we want to use it on. You can download the script yourself if you want, but we're going to use the CDN version for the sake of simplicity.

Add the following script tag just before the closing </body> tag.

<script src="https://cdn.jsdelivr.net/gh/ekalinin/typogr.js@0.6.7/typogr.min.js"></script>

There aren't any dependencies, so this is all you need to do to load the library!


Usage with Surreal CMS

Now we need to tell typogr.js what content we want it to process when the page loads. If you're using Surreal CMS, you can tell it to process all of your content regions (i.e. any element with the cms-editable class).

Add the following script just before the closing </body> tag, but after typogr.js.

<script>
  // Enable typogr.js when the page loads (unless we're in the editor)
  if (!window.isCMS) {
    window.addEventListener('DOMContentLoaded', function() {
      var regions = document.querySelectorAll('.cms-editable');
      var i;

      for (i = 0; i < regions.length; i++) {
        regions[i].innerHTML = typogr.typogrify(regions[i].innerHTML);
      }
    });
  }
</script>

You might notice the window.isCMS conditional — this is one way we can detect the CMS. We're basically telling typogr.js to run on the live webpage, but not in the editor.

Usage without Surreal CMS

If you're not using Surreal CMS, you'll need to identify which elements you want to process. For example, if your content is in <div id="content"> you would do something like this.

<script>
  window.addEventListener('DOMContentLoaded', function() {
    var el = document.querySelector('#content');
    el.innerHTML = typogr.typogrify(el.innerHTML);
  });
</script>

Tip

If it's not working, double check that you've loaded typogr.js first and that you're targeting the right element with your selector.


That's it! From now on, your pages will automatically feature better typography without any additional effort.