DEV Community

Harris Reynolds
Harris Reynolds

Posted on

Find and Save New Fonts with the Google Fonts Explorer

Font selection is a fun part of building a website or application, but it isn't always easy to find new and interesting fonts with a platform like Google Fonts.

There are one thousand, five hundred and twenty-one fonts in their collection!

So I decided to build a Google Fonts Explorer to make it easy to find new fonts that I like.

Here's how I built it and what its key features are.

A full list of all of the Google fonts is available via their api here as JSON.

Load up the JSON in Javascript and render the available fonts in a list within a HTML page.

Using a JS framework like Vue or React you can easily display the list of available fonts.

Next let's write a handler that can load a font into the current page.

Add a click handler to each element that is responsible for rendering the font family.

Here's a couple Javascript functions that show how I did this:

injectFont(font) {
    let weights = this.availableWeights(font)
    let url = 'https://fonts.googleapis.com/css2?family=' + font.family + weights
    let link = document.createElement("link");
    link.href = url;
    link.rel = "stylesheet";
    document.getElementsByTagName("head")[0].appendChild(link);                
}

availableWeights(font) {
  let weights = font.variants.filter(variant => variant.indexOf('italic') < 0).join(';')
    weights = weights.replace('regular', '400')
    return `:wght@${weights}
}
Enter fullscreen mode Exit fullscreen mode

This will make the font you click available to the current page by injecting the stylesheet link for the Google font into the head element of the page.

Lastly you can dynamically change the font of any element on the page with a bit of code like this:

const displayElements = document.querySelectorAll(".display-element");
displayElements.forEach((displayElement) => displayElement.style.fontFamily = selectedFont.family)
Enter fullscreen mode Exit fullscreen mode

This is just a high-level overview of how you can build a Google Fonts Explorer. If you are interested you can just view the full source on the page I linked to above to see all the gritty details!

The public version I linked to includes a few advanced features that make it super fast to explore fonts and save them.

You can use the filters and the up and down arrow keys to narrow down your search and then quickly iterate over them.

As you find fonts you like you can save your favorites (sign in required).

I hope you enjoyed the article and that you find the Google Fonts Explorer useful.

Feel free to hit me with questions or feedback!

Top comments (0)