Web Design


Using JS Functions in our Blog

What are functions?

A function is a set of statements that performs a task or calculates a value that we need. We will be using them for a few things.

How do I create a function?

Creating a function is as simple as writing function and giving it a name. Then, we specify how much data we want to give it for the code to run.

Let's make our loop into a function

// function that creates every card for the posts
function getPosts() {
  // for the number of cards, create them. if you add more data, this auto-updates
	for (var i = 0; i < title.length; i++) {
		document.write("<div style=\"margin-top: 20px;\"></div><div class=\"card\"><div class=\"card-body\"> <h5 class=\"card-title\">" + title[i] + "</h5><h6 class=\"card-subtitle mb-2 text-muted\">" + dates[i] + "</h6><p class=\"card-text\">" + summaries[i] + "</p><a href=\"https://" + domain + ".neocities.org/post" + links[i] + ".html\" class=\"card-link\">View Post</a><a href=\"" + "sms://&body=https://"+domain+".neocities.org/post" + links[i] + ".html\" class=\"card-link\"><i class=\"fas fa-share-square\"></i></a></div><div style=\"margin-bottom: 10px;background: linear-gradient(to right, " + grads[i] + "); width: 100%; height: 10px;\"></div></div>");

We named our function getPosts. Even though we have no parameters, we need to still put the parenthesis. This is all the code we need for our home page. Let’s move onto our post pages.

Post Pages

Our post pages will contain the title of the post, date, and text. The following functions take in variables named i. Since Javascript is type-safe, we don’t need to give it a variable type. This first function changes the tab title of your browser to the post name. It takes in a number, finds the title with the same number, and returns a title of that variable.

// function to get the page title the same as the blog post title
function pageTitle(i) {
	document.write("<title>" + title[i] + "</title>");

This function takes a number, finds the variables it needs, and generates the content on our post page.

// function that uses the data to create the blog post pages
function post(i) {
	document.write("<h1 class=\"blog-title\">" + title[i] + "</h1><p class=\"blog-title\">" + summaries[i] + "</p><div style=\"margin-top: 30px;\"></div><p class=\"blog-title lead\">" + text[i] + "</p><div style=\"height: 40px; width: 100%;\"></div>");

Finally, this function is the same as the others, but gives the gradient scheme we need.

function gradient(i) {
    document.write("<div style=\"height: 10px; width: 100%; background: linear-gradient(to right, " + grads[i] + ");\"></div>");

Almost there!

We are almost there to the end of this website. In the next and final lesson, we will be plugging in everything into our index.html file.