Share


How to Deal with Dynamic Text in HTML Using Spreadsheets

by Astha Sharma on 2021-03-10

What is Dynamic Text?

Dynamic text is text that is constantly changing or being updated. Such as the date, live reports, news, blog posts etc.

If you are running a blog or want to display live stats on your website it can get difficult to constantly update them through the backend. In this tutorial, we will be using API Spreadsheets to replace a backend with a Google Sheet.

Full Code

On my personal website, I want to have an updated About me section where I can list the tv show, music, quote, and coding language I am learning that week.

However, as you can see with our article on deploying a site, it can get time consuming to have to upload the HTML file every time you want to change something.



We will be going through each section but here is how it looks right now. You can also view it live here.


ApiSpreadsheets

Start with creating a Google Sheet

Since we are only going to be using it to change one section, there is only going to be one row that we can work on and keep changing.

Api Spreadsheet

I am going to be displaying the week, show I'm watching, favorite Music, coding language I'm learning, and my favorite quote.

So in my spreadsheet, my column names are Week, Show, Music, Language, Quote

Connect your Google Sheet on APISpreadsheets.com

Now, we need a way to get our data from Google Sheets onto our website.

To do this, we are going to be using our tool to convert the Google Sheet to a REST API.

It’s okay if you don’t understand REST APIs fully. All you need to know is they let you read or write data using a standard protocol available through Javascript

Whenever I want to change the data, I can easily do so on the Google Sheet.

Make an account if you don’t have one already (it’s free for up to 3 files!) and choose the file you want.

Once you have uploaded the file, checkout the quick tour to get a deeper understanding of all the features.

For this tutorial, we will only be reading our spreadsheet so click on the “Read” tab and Javascript Code Sample


api spreadsheets

We will be copying and pasting this Javascript code sample in our code.

You don’t have to do that now. We will show you when to do it below. Just keep the tab open.

Open Up a Text Editor of Your Choice

I will be using Sublime Text but you can use whatever you are comfortable with, such as Atom or Notepad.

Create HTML file

Create and set up an HTML page with the <head>, <style> <body>.

In the <body>, we are going to include 2 div tags that will be crucial in:

  1. Displaying our data from Google Sheets, <div id= “allElems”>
  2. Showing a default message if there is an error <div id= “errorMessage”>


Copy the Javascript code from API Spreadsheets

Place it at right before the end of your </body> tag in between <script> </script> tags.



Add CSS

You can either create a separate CSS file or just add a <style> tag in your <head>.

Here is my full CSS:

                    
<style>
@import url('https://fonts.googleapis.com/css2?family=Comfortaa:wght@500&display=swap');
		body{
			background-color: whitesmoke;
			}
		#about{
			font-family: Comfortaa;
			text-align: center;
			padding: 100px 50px 50px 50px;
			}
		#display{
			font-family: Comfortaa;
			text-align: center;
			border-radius: 10px;
			background-color: #A9C9FF;
			background-image: linear-gradient(66deg, #A9C9FF 0%, #FFBBEC 100%);
			padding: 20px;
			height: 50%;
			margin: 0 30px 0 30px;
			}
		.elemsRow{
			text-align: center;
			}
		#allElems{
			display: none;
			}
		#errorMessage{
			display:none;
			}
		.Week{
			display:inline-block;
			text-align: center;
			padding-right:5px;
			}
		.Show{
			display:inline-block;
			text-align: center;
			padding-right: 5px;
			}
		.Music{
			display:inline-block;
			text-align: center;
			padding-right:5px;
			}
		.Language{
			display:inline-block;
			text-align: center;
			}
		.Quote{
			display:block;
			text-align: center;
			}
</style>
                
                

CSS Code for our 2 crucial <div> elements

We will be styling our 2 crucial elements.

We will set <div id= “allElems”> and <div id= “errorMessage”> to NOT display initially.

This is because when the website initially loads, we will be fetching our data from Google Sheets and won’t have anything to display.

We also won’t know till the fetch is complete whether to show the error or not.

                    
#allElems {
  display: none;
}
#errorMessage {
  display: none;
}
                    
                    

The FULL Javascript Code

We are going to be adding A LOT more to the fetch code. The final code in the <script> tags will be as follows.

Again, we will be breaking it down block by block.

Get our 2 crucial elements & Set up an Error function

                    
let allElemsElm = document.getElementById("allElems")
let errorMessageElm = document.getElementById("errorMessage")

function setErrorDisplay(){
allElemsElm.style.display ="none"
errorMessageElm.style.display = "block"
      }
                    
                    

We start off by getting our 2 crucial elements using Javascript’s document.getElementById function and passing it the id of our element.

We also set up a function for if there is an error. This function sets the display of allElems to be none (aka not display). And turns on the display for the errorMessage.

We will be using the function whenever there is an error in fetching our data.

Fetch the Data

We start off by fetching the data. If you copied and pasted your API Spreadsheets code correctly, the URL of your file should be automatically on there.

This URL needs to match your file and you can always get it from your dashboards

If your fetch is successful, then the data from your Google Sheets will be in an array in the returned object with a key of “data”. See my returned object below.

                    
{"data": [
           {
             "Week":"March 8th",
             "Show":"Euphoria",
             "Music":"Daft Punk",
             "Language":"JavaScript",
              "Quote":"“You can't stop the waves, but you can learn to surf” - Jon Kabat-Zinn"
           },
}
                    
                    

Each element in the array will correspond to the row in the Google Sheet. The array element will be an object with the key being your Column Name and its value for the row. We only have one row we want to change.

We get this array by accessing the “data” key from the returned object.

                    
    const yourData = data["data"]
                    
                    

rowInfo in yourData

Since we only have one object/row, we do not need a loop and can call this rowInfo.

                
        let rowInfo = yourData[0]
                
                

This will get our 1st (and only) element from the sheet.

First we will create a container <div> that will hold our elements for Week, Show, Music, Language, and Quote. We will call this rowInfoDiv. We will give it a class called elemsRow so we can style it later.

                
                let rowInfoDiv = document.createElement("div")
                rowInfoDiv.classList.add("elemsRow")
                
                

Then we will create elements for each of our 5 values.

Let’s create the element for Week. We will make this a <p> and call it rowWeek.

                
                let rowWeek = document.createElement("p")
                
                

Then we will create a text node that contains the Week text from our rowWeek object. We will call this rowWeekNode.

We want to add some text to be displayed before the Week date. So we add the string "The week of " and add it with + so it can say "The week of ____".

                
                let rowWeekNode = document.createTextNode("The week of " + rowInfo["name"])
                
                

Remember to leave a space after your string or add blank quotes " " to properly display your sentence.

We add this text node to our p element and give it a class called “Week” so we can style it later.

                
                rowWeek.appendChild(rowNameNode)
                rowWeek.classList.add("Week")
                
                

Api Spreadsheets

Our Show, Music and Language elements follow the same method.

                
                    let rowShow = document.createElement("p")
                    let rowShowNode = document.createTextNode("I have been binging " + rowInfo["Show"] + ",")
                    rowShow.appendChild(rowShowNode)
                    rowShow.classList.add("Show")

                    let rowMusic = document.createElement("p")
                    let rowMusicNode = document.createTextNode("listening to " + rowInfo["Music"] + ",")
                    rowMusic.appendChild(rowMusicNode)
                    rowMusic.classList.add("Music")

                    let rowLanguage = document.createElement("p")
                    let rowLanguageNode = document.createTextNode(" and practicing up on " + rowInfo["Language"] + "! ")
                    rowLanguage.appendChild(rowLanguageNode)
                    rowLanguage.classList.add("Language")
                
                

For Quote I wanted my static text "A quote that got to me:" to remain roman, but the quote to be italicized.


api spreadsheets

First I created a separate p element for just the static text and called it rowQuote.

                    
let rowQuote = document.createElement("p")
let rowQuoteNode = document.createTextNode("A quote that got to me: ")
rowQuote.appendChild(rowQuoteNode)
                    
                

Then I created an i element for our object "Quote" and called it rowQuoteItalics.

                    
let rowQuoteItalics = document.createElement("i")
let rowQuoteItalicsNode = document.createTextNode(rowInfo["Quote"])
rowQuoteItalics.appendChild(rowQuoteItalicsNode)
                    
                

Now I add both rowQuote and rowQuotesItalics to the class "Quote".

                    
rowQuote.classList.add("Quote")
rowQuoteItalics.classList.add("Quote")
                    
                

Now we have our five components for our row in the Google Sheet: rowWeek, rowShow, rowMusic, rowLanguage, rowQuote, and rowQuoteItalics.

We add these to our container <div> which we called rowInfoDiv.

                
rowInfoDiv.appendChild(rowWeek)
rowInfoDiv.appendChild(rowShow)
rowInfoDiv.appendChild(rowMusic)
rowInfoDiv.appendChild(rowLanguage)
rowInfoDiv.appendChild(rowQuote)
rowInfoDiv.appendChild(rowQuoteItalics)
                
                

And finally we add rowInfoDiv to our crucial div <div id= “allElems”> which we obtained at the start of the code and called allElemsElm.

                
                allElemsElm.appendChild(rowInfoDiv)
                
                

The allElems div will contain all the rowInfoDiv elements in our row.

Now we want to display this div and hide errorMessage.

                
                allElemsElm.style.display = "block"
                errorMessageElm.style.display = "none"
                
                

Dealing with All the Errors

There are multiple errors that can happen. We can deal with them in the catch blocks.

We also deal with an error if the API return code is not 200. This means that there was a problem getting the data.

We created a function before that shows the errorMessage and hides the allElems.

We call this function setErrorDisplay() whenever we encounter any error in our code.

The message that will display is what we wrote in our errorMessage div. I have put a generic sentence "I've been watching Bojack Horseman (again), listening to The Weeknd, and practicing up on Javascript!"


api spreadsheets

To test if your error message works, add an extra number or letter to your API link.

Run this file

Open the file in any browser of your choice and everything should work and look like this picture.

ApiSpreadsheets

Now I can quick change this once a week from my Google Sheet instead of having to upload a new file each time!

Closing Remarks

We hope you use this for times you need a quick way to deal with dynamic text!

Feel free to reach out to us at info@lovespreadsheets.com if you have any questions.