How to code a Word of the Day app in JavaScript, and turn it into a Chrome Extension (Part 1)

l-emi
Chingu
Published in
7 min readOct 29, 2016

Welcome! In this article I’m going to walk you through making a Word of the Day app in JavaScript. In Part 2, we’re going to optimize it for the Chrome Store as an Extension. Here is what the finished product will look like, and here is the entire code. Let’s get started!

First of all, let’s list what we want our app to do:

  • Displays the date on the top of the page
  • Displays the word of the day, its definition and pronunciation in the middle of the page
  • Loads a new background every time you refresh the page

Simple! Now before we get started, I’m going to list a few resources that you’ll need to make this app:

  • The Wordnik API. This is what we’ll be using to get the word of the day. You want to sign up here, then sign up for an API key. When you’ve done that, click on your username at the top right of the page, and click on settings. Scroll down to the bottom of the page where you’ll see your key.
  • Unsplash. Unsplash has a ton of free high-resolution photos that you can use for absolutely anything. You want to make an account and create a new collection specifically for this project, then go about collecting photos you want to display in the background of the app.
  • Postman. Postman is a Chrome and Mac App that lets you work with APIs efficiently. This one isn’t necessary but I highly recommend it; it’ll make using APIs much simpler for you.

The HTML & CSS

When I was coding this I hadn’t thought of turning it into a Chrome Extension, so I linked to all my script files using a CDN (which is what you’ll see in the code I posted on Github). However, Chrome only allows local scripts and objects to be loaded from your app’s package. The easiest way to load externally served resources like jQuery is to download the relevant library locally and package it with your extension (read more).

Basically, just download the scripts you need and store them in the app’s directory to link to them from there. Instead of:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Have:

<script src=”scripts/jquery.min.js”></script>

Since the main focus of this article is going to be the JavaScript and making the extension, I’ll just link to the HTML and CSS I used.

The JavaScript

Here’s the entire file, commented out. So, let’s take care of the background images first.

To get a random image from the Unsplash collection you created, you use the link “https://source.unsplash.com/collection/” and tag on your collection id, which you can find by going to the actual collection and copying the numbers in the link.

You want to place the image so it fits perfectly on the user’s screen, so we’re going to use this function:

function placeImage(w, h) {
w = window.screen.availWidth;
h = window.screen.availHeight;
document.body.innerHTML += '<img src=' + '"https://source.unsplash.com/collection/347929/' + w + 'x' + h + '"' + ' id="bg" alt="">';
}

It grabs the user’s screen height and width, and perfectly positions a random image from our collection as the background.

Next we need to get the current date and place it at the top of the screen.

function getDate() {
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var date = new Date();
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var marker;
if (day == 1 || day == 21) {
marker = "st";
} else if (day == 2 || day == 22) {
marker = "nd";
} else if (day == 3 || day == 23) {
marker = "rd";
} else {
marker = "th";
}
document.getElementById('date').innerHTML = monthNames[monthIndex] + ' ' + day + marker + ' ' + year;
}

In the first part of the function, we need to create an array of the months. This is because just calling date.getMonth(); will get you a number. For example, instead of September you will get 8 - the index of the month. We can use this number to specify which month we want in the array.

We also need to create a simple if/else statement so that our date has a st, nd, rd or th on the end. To finish, we put this date into its HTML container.

If you’re interested, here’s a much shorter way to do this from Stack Overflow. Beware though, it’s confusing:

function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}

Onto the API calls!

If we visit the Wordnik documentation, we are presented with a list of things we can do. Click on Words then the second option.

Then, scroll till you find the button Try it out!

This is what the code will look like to get the word of the day and its definition:

function theWord(callback) {
var baseUrl = "https://api.wordnik.com/v4/words.json/wordOfTheDay?api_key=";
var apiKey = "a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5";
var apiUrl = baseUrl + apiKey;
//A promise is needed here, as without it the second API call would return before pronounceIt() can execute the callback, and we would get, well, nothing, instead of the actual word.
return new Promise(function(resolve, reject) {
$.ajax({
type: "GET",
url: apiUrl,
dataType: "json",
success: function(data) {
$("#word").append(data.word);
$("#defin").append(data.definitions[0].text);
resolve();
}
});
});
}

Note: the API key used in this code snippet is the default one from Wordnik. Substitute it with your own key.

As the comment says, we’re using a Promise so that the second API call can return only after the pronounceIt() has executed the callback.

Have you downloaded Postman? Go ahead and open it. Select GET and paste in the apiUrl (for example, http://api.wordnik.com:80/v4/words.json/wordOfTheDay?api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5). In the success function we are going to append the word and its definition to their respective containers.

In Postman, we can now search for the data we want. The word is quite simple to find. It is just data.word.

Next up, the definition. Scroll down until you see definitions. The actual definition is under text, in the first object of the array. Therefore, we use data.definitions[0].text.

When the word and its definition have been placed inside of their containers, the Promise will resolve.

We also want to show the word’s pronunciation. To do this, we need a new API call.

function pronounceIt() {
var baseUrl = "https://api.wordnik.com/v4/word.json/"
var apiKey = "1380d58b8b5c33325130c0e8f340be6bc6fba6f7bb65bfc6f";
var word = $("#word").text();
var apiUrl = baseUrl + word + "/pronunciations?useCanonical=false&typeFormat=ahd&limit=50&api_key=" + apiKey;
$("#link").attr("href", "http://www.dictionary.com/browse/" + word + "?s=t"); //link to dictionary.com page
$.ajax({
type: "GET",
url: apiUrl,
dataType: "json",
success: function(data) {
if (data.length > 0) {
var input = data[0].raw;
var output = "[" + input.slice(1,-1) + "]";
$("#pronun").append(output);
}
}
});
}

In this code snippet, you can see that I split the URL up in bits. There’s the base URL, the API key, and the word. We will grab the word from its container, which is why we’re using:

var word = $("#word").text();

Next, we’re simply linking the word to its dictionary.com page.

Back to the docs we go! This time, click on word, then GET /word.json/{word}/pronunciations.

It gives you a few options to select before giving you the Request URL. For the word parameter, just type in test then click Try it out! again. Copy the URL, and plug it into Postman. The pronunciation we want to use will be under data[0].raw.

In the success function, we’re saying that if there is a pronunciation for the word (some words don’t have one), find it, take away the () brackets and place it in [] brackets (it just looks better, right?). Then, append it to its container.

Now the only thing left to do is put it all together and fade in the image and text.

$(document).ready(function() {
placeImage();
getDate();
theWord().then(pronounceIt);
$('img').css('opacity', 1);
$('body').css('opacity', 1);
});

This is simple. When the page loads, place the background image and date. Then, once the Promise for the word has been resolved, run the API call for the pronunciation and place that. Finally, fade it all in.

Yay! We’re done! I encourage you to use the Wordnik API to make variations of this app to solidify what you’ve learned.

If you want to learn how to transform your app to a Chrome Extension, read on to Part 2.

--

--