Search for:
SITK - Pie Shop 5of7 Featured image

Exciting Web Development Journey – Pie Shop Website 6/7


Welcome back to Sharing Is The Key. Now that you are already acquainted with JavaScript basic concepts, let’s push a little bit further and create some interactivity in the Pie Shop website.

In this post, we cover some of the building blocks you need to create interactive web apps. We’ll discuss how to write code that can respond when certain things happen in the browser, like when the page loads, when you click a button, and so on. We’ll also review a wide array of built‑in features and functionalities available to you through JavaScript as you build web apps. Finally, we cover how to determine browser support for different features and what to do if that feature isn’t yet supported.

Selecting Elements

One of the fundamental actions that you’ll use JavaScript for working with the web page is selecting elements on the page. Going back to our sandbox.html we dealt with in the third post.

As we look at the HTML, each project is made up of a section element with an id, which represents each specific project, and they both have the class of project.

So when I want to access one, specifically, I can use the id attribute, and when I want to access these elements together as a set, I can use the project class. Inside the project, there is a title, an image and a paragraph for each project.

Now to use JavaScript to access these elements, I can do several different ways, and one of the first is to use a function called getElementById.

If we look at the document just in and of itself, we could see that this object represents the web page or the document running within the browser.

SITK- Pie Shop - selecting elements - document

By calling document.getElementById and pass in an id value, what it returns is a reference to the section element because it has the id of project-1.

SITK- Pie Shop - selecting elements - document.getElementById()

Now that works great for accessing elements with a specific id, but what if I want to select items based on their class name? Well, I can do that very easily as well. Here, I can use document.querySelector. Now, what we pass into the querySelector function will seem very familiar to you. It will take the same type of selectors that we used in building CSS rules. So to access my project class, I type in .project.

SITK- Pie Shop - selecting elements - document.querySelector()

Now the querySelector function returns the first match of your selector. Here, you can see that it returned the section for project-1 because that was the first item that had the project class.

Now we can get all of them just as easily by calling document.querySelectorAll. When we pass in .project, what’s returned is a node list of all the matching elements.

SITK- Pie Shop - selecting elements - document.querySelectorAll()

The queries you can pass into the querySelector function can be straightforward like I’ve shown you or even a little more complex. Retaking a look at the HTML, I have a img element with a src attribute that has a value of So we can take these same values and format them in a selector to use with querySelector.

SITK- Pie Shop - selecting elements - more complex document.querySelector()

Now there is one more thing I want you to notice as well, see how I used the double quotes on the outside of the selector and the single quotes on the inside. The quotes on the inside are necessary to tell the selector that we’re searching for a string value that the src will be equal to, but we can’t use the double quotes because that would signal to the browser that the selector was going to end early. Any time you need to use quotes inside of quotes, you can use the single quotes inside the double or use the double quotes inside the single. The important thing is you only have to be consistent.

Working with Elements

Now that we’re able to select elements on the page let’s see what we can do with them. One of the actions that you can take against an element is to change attributes in JavaScript.

So with this Sharing is the key! link here right now, if I click on it, it’ll open up in the same browser tab as my sandbox page. And if we look at the HTML, the anchor has an href attribute and a class attribute.

SITK- Pie Shop - working with elements - link

But there’s an attribute that we can add named target that allows us to designate the destination of the link location. So let’s go down to the script on the page and add a little bit of code.

SITK- Pie Shop - working with elements - setAttribute()

Now what I’m doing here is using document.querySelector to select the only anchor element on the page. Once I have access to it, I can call the setAttribute function and tell it that I want to add an attribute target and set its value to blank. All right, well, let’s save it and switch back over to our page and see how it behaves now. Now when I click on the link, it opens up in a new tab.

SITK- Pie Shop - working with elements - setAttribute(target, _blank)

The setAttribute function works to create an attribute that isn’t there yet or update an attribute’s value.

So here I’ll open up the developer tools, right‑click on the link, and select Inspect. When I come into the Elements pane, it automatically creates the $0 variable to select the element. And so I wouldn’t use $0 when I’m coding a web page. But here, I’d like to show you how you can do it for experimentation within the browser development tools. So now I’ll switch over to Console, and I’ll verify I have a value for $0.

SITK- Pie Shop - working with elements - $0 variable

So this variable is now pointing to this element. Now from there, what I can do is I can ask for the value of a specific attribute. By calling getAttribute and passing in the name of the attribute that I want to look at, I get the value of our new target attribute.

SITK- Pie Shop - working with elements - $0.getAttribute(target)

I could also ask for the href value. And I could also remove an attribute. Passing in the attribute name removes the attribute from the element.

SITK- Pie Shop - working with elements - $0.removeAttribute(target)

Now you can see that the HTML has been updated so that the target element is not there.

SITK- Pie Shop - working with elements - $0.removeAttribute(target) - result

So now when I click on the link, instead of this opening up in a new tab, it opens up in the same tab, all because we’ve removed that attribute.

Now there’s one attribute that acts a little bit different than the others, and that’s the class attribute. So in the next section, I’d like to show you how to work with the classList HTML attribute.

classList Property

Selecting elements is the first step, but once you have access to those elements, it opens up all kinds of possibilities for you to do something with them. Here we have our page that has our projects on it, and each section has a class list with project and desktop. Now, we’ll run some code that will update the classes that are applied to the project.

SITK- Pie Shop - classList Property - class list values

But first, let’s go to the CSS style sheet and add this rule for the dark class to make things easier to understand.

SITK- Pie Shop - classList Property - dark rule

I want to locate an element with the class project and desktop and add dark to the class list. When we take a look at the web page with the dark class applied, we could see that the project-2 is rendered with a dark background.

SITK- Pie Shop - classList Property - dark class applied to project-2

Now, what I just did was to add it directly here into the HTML. And so now I’d like to show you how to do the same thing using JavaScript. So we’re back to the web page’s default state, so I can use document.querySelector to get access to the element with the project class. When we look at the project variable, we can see that the first project is selected.

SITK- Pie Shop - classList Property - using querySelector

Now, from there, I can change the classes that are associated with this element. You might think that I could go to project.class and set that equal to something, but that does not work in JavaScript. The word class is a reserved word. And so here, what we’ll use is a class list. By accessing the class list, I can call the add function and pass in a class name. Here, I don’t add a dot before the name. Because this isn’t a selector, I’m passing in a name. And so now, as I press Enter, the list of classes associated with that element now includes dark, and in fact, we can look at that list here and see it returns both project, desktop and dark.

SITK- Pie Shop - classList Property - adding dark to the project class list

Now, what if I want to remove it? Well, I can call project.classList and run the remove function. And so now, when we look at the class list, there are only project and desktop.

SITK- Pie Shop - classList Property - removing dark from the project class list

Script Tag

One of the elements that you’ve seen me using a lot but we haven’t discussed yet is the script element in depth. Now the script tag is the element that we use on a page to execute scripts. The location of the script tag is essential. Let’s think about how a website works. When you send a page to the browser, the code is processed from top to bottom. Remember, HTML and CSS are responsible for the structure and layout of the page, while the scripts are responsible for its behaviour. I bring all this up because it’s for these reasons we want the script tag near the bottom of the page.

Often it shows up as the last element before the body’s closing tag. It ensures that our pages aren’t halted from loading and being styled due to a script that didn’t work quite right. So as you’ve seen throughout this post, I’ve added JavaScript to the script element.

There are times, probably more often than not, when you’ll want to move the script into an external file. We move JavaScript into its file for a lot of different reasons:

  • One is that the scripts are easier to write and maintain when they’re in dedicated files. You can load as many script files as you want into a page, and by splitting up the code and the logic, just makes your applications easier to work with.
  • The second main reason is that browsers make copies of files that they request from the server. We call it caching. When a file is cached, the browser loads its file from a saved copy rather than making a new request to the server. Now, this speeds up the web a lot. So if you have a script file that many pages of your site use, then adding it as an external file makes a lot of sense so you can take advantage of browser caching.

There are other excellent reasons to use external scripts, but these are the two main ones that are relevant right now. So I have an external script provided for us, and just so that you can see the location, I created sandbox.js right next to sandbox.html and moved the code from the script tag in the sandbox.html page into the sandbox.js file.

SITK- Pie Shop - script tag - moving javascript code to a dedicated file

Now to reference it, the script tag will have a source attribute that points to sandbox.js. And then, I need to add a type attribute and set that equal to text/javascript. This attribute is important because it tells the browser what language the script is coming in as. The only client‑side scripting language we use is JavaScript, but it’s added here just for completeness with modern web development. Now some tags within an HTML page are self‑closing. So if you notice, the meta tag up here doesn’t have an associated closing tag. The script tag does need the closing tag, though. Even though we don’t put anything in between the script tag, we still have to close it here explicitly. When we save the file, the page reloads, and we get the Sharing is the key! link working the same way as before.

SITK- Pie Shop - script tag - linking javascript to html

Next, let’s take a look at how the window object is used inside of the browser and through JavaScript.


The Window object is the context for scripts running within a web browser, and we’ll use Sharing is the key website to illustrate.

SITK- Pie Shop - window - sitk website

So the window generally refers to the window that’s running inside a current tab. So if I open up the About page in a separate tab, there are two different Window objects where your script will run, even though they’re technically within the same website. They’re independent pages, so they get a different context.

SITK- Pie Shop - window - sitk website - about page

The window hosts the document object, which is the DOM for this tab. So if we take a look at the window, you can see scores of functions and properties available off the window. And much of the functionality of the browser is available off of the window object.

SITK- Pie Shop - window - sitk website - window object in the about page

Now, from here, we have access to things like the location of the browser tab. We can get all kinds of information about the URL of the page and even the different segments that make up this location. So we could do an entire course on the window object inside the browser. But for now, what you need to know is that we’ll use the window object to get access to the built‑in functionality of the browser.

SITK- Pie Shop - window - sitk website - window.location info


If you use nothing else inside the browser developer tools, you will use the debugger. The debugger allows you to stop code from running at a specific point so you can inspect what’s happening right at that line of code.

Now, I’ve written a simple script here, and if you haven’t already noticed, I’ve introduced a bug into my code. So I’m concatenating together my first name and last name, but here, when I go to use them together, I use the variable called firstName instead of first.

SITK- Pie Shop - debugging - known error

So, if we save the file, you’ll notice that I get a reference error, and it says firstName is not defined. Now, this is a straightforward script. We can see the error very quickly.

SITK- Pie Shop - debugging - save and get an error

But let’s imagine for a moment that this bug is hard to find. Within the browser developer tools, I can go over to the Sources tab, and when I click on the sandbox.js file, it shows me right where I have an error for this line of code. Now, if I come down to the line numbers and I click on line 2, you’ll notice that it’s highlighted with this blue arrow. It is called a breakpoint, and you can see in the window on the right that it shows the list of breakpoints.

SITK- Pie Shop - debugging - set a breakpoint in the source tab

A breakpoint is a point at which the execution will break, or essentially stop, and allow you to examine what’s going on in the code. So now, with that breakpoint set, I can refresh the page and notice what happened. It highlighted the line, and it shows up at the top that it’s paused in the debugger.

SITK- Pie Shop - debugging - execution stopped at the breakpoint

Now, as I look around on my page, I can hover over variables, and I can see at the variable named first has a value of "John". The variable of last is not yet declared because we haven’t executed this line yet.

So, I’ll click on Step over the next function call button, or you can press F10, or CTRL+apostrophe, either one of those will work, and now the next line of code has been run.

SITK- Pie Shop - debugging - step over the next function call

So the variable named last now has a value of "Smith". But you’ll notice it didn’t keep going. It stopped at the following line of code. So at this point, I can hover over last and see that I have a value. And then I see firstName. Well, that doesn’t have value. And so, by stopping the code as it’s executing, I have a much better chance of figuring out what my problems are.

So, here we’ve realized, firstName is not the variable that we need. What we need is to call that first. So now I can switch over to the editor. Make the change. Remember, the execution is still stopped on line 3, so I’ll let it run by clicking on the paused in debugger button at the top of the page and let’s refresh it, and now it hits the breakpoint again.

SITK- Pie Shop - debugging - debugging again with the code fixed

So first has a value of "John", step over the following line, last has a value of "Smith", and first and last now have values. I fixed my bug, and now the name variable has "JohnSmith" as its final value. On the right-hand side, you’ll notice over here that it shows the current script that’s running and all the variables that are currently in scope and their values.

SITK- Pie Shop - debugging - checking the final result

By setting breakpoints and using the browser’s debugging tools, you have a lot of power available to you to debug your applications. Now that we have a good view of what it takes to write and debug code let’s start writing some code against the browser and find out how to work with HTML elements on the page.


Events, in programming languages, just like in real life, signal when something happens. When an event occurs in a program, the application sends a notification to the rest of the code, essentially saying, hey, something happened here. You get to select which messages you want to respond to this event. Now, for instance, there’s an event that fires when the page loads. You can also listen for an event that fires as a button is clicked. You can even tap into an event that lets you know when a change in the orientation of your mobile device has occurred. And these are just a few, among many, events that you can use in your app. In JavaScript, you set up your code to listen for events. Let’s take a look at the function that allows us to respond to these events, and that function is called addEventListener.

addEventListener Function

AddEventListener is the function you use to run some code when a given event takes place. The syntax for this function is made up of a few different parts. Here addEventListener is being called off the window object. But now we need to tell the browser which event we’re interested in. The name of the event is added first between quotes here because the name is a stream. Now there are dozens of events to choose from, and in the coming examples, I’ll show you how to use a few.

SITK- Pie Shop - addEventListener - first argument

The second argument of the function expects a function. It is similar to how the forEach function worked when we spoke about arrays, where the function defined here is called when the event notification is sent.

SITK- Pie Shop - addEventListener - second argument

This is an anonymous function, and it is being called gets a reference to an object that contains information about the event that was just raised. Often you’ll need to access different information to find out more about what’s happening in the program, and that will be available within the event object.

SITK- Pie Shop - addEventListener - second argument - event object

Inside the function is where you write the code that’s meant to respond to the event.

SITK- Pie Shop - addEventListener - second argument - logic content

Okay, let’s look at some actual implementations and how you can respond to a few different events in JavaScript.

Demo: Events

Here we are back with our sandbox page, and one of the first events that I’d like to look into is to know whether or not the page is completely loaded within the browser. This is important because our page is represented in the browser through the Document Object Model.

SITK- Pie Shop - demo events - sandbox page

Now, let’s recall our discussion from cascading style sheets, where we talked about the Document Object Model, or the DOM. In that case, it’s an in‑memory hierarchical representation of the elements that make up a web page. When the browser requests a page, the server’s response includes HTML that’s read by the browser. Based on the HTML structure, elements are created in‑memory that correspond to the markup in the page.

SITK- Pie Shop - demo events - abstract DOM representation

Now load times can vary depending on many factors. Sometimes web pages load so quickly that it seems instantaneous to our eyes. Still, there’s always a certain amount of time that elapses before a web page is completely loaded and rendered inside the browser to a computer. Since there’s this delay in time, even if it’s slight, the code we write needs a way to know that, indeed, that page is loaded before attempting to run.

The event that tells us that the page is loaded and ready to work is called DOMContentLoaded. So the first thing that we want to do is go to the window object and call addEventListener for DOMContentLoaded. Then we’ll create an anonymous function that’s called when the event fires. Within the body of this function, we can add in our logic that runs as the page loads. So we’ll log out to the console saying that the page is loaded.

SITK- Pie Shop - demo events - DOMContentLoaded

When we save the page, it’s reloaded, and only until all of the page contents are loaded into memory. Each of the HTML elements are processed in the DOM. The DOMContentLoaded event is fired. We get the console to report that the page is loaded. Our page is elementary, so it goes fast, but this is the place where you want to begin writing code if you’re going to use any elements on your HTML page.

SITK- Pie Shop - demo events - DOMContentLoaded - result

If we wanted to interact with a button on the page, we could do that simply here within this event. I’ll start by creating a new element for a button that we can click on. I’ll assign the button with the id of click‑me and the text of Click Me.

SITK- Pie Shop - demo events - creating a button element

So now, down at DOMContentLoaded, I can add in the logic to interact with my element. The first thing that I want to do is select the element on the page. Here, I’ve used the querySelector function to pass in an id selector to find that element on the page. Next, we’ll add an event listener on the button to listen for the click event. And with that, I can log out to the console that the button was clicked.

SITK- Pie Shop - demo events - adding code to the event listener function

So, as I save the page and reloads, I get a button here rendered on the page. So when I click on that, I get a message logged to the console, saying, “The button was clicked.”.

SITK- Pie Shop - demo events - adding code to the event listener function - result

And lastly, I’ll show you how to handle the event when the device orientation changes within the browser. It is an event that only fires for mobile devices, so I’ll show you how we can simulate it within the desktop browser. First, we’ll add an eventListener for orientationChange off the window object. Now we can look at the screen object to get orientation information about the device. We can get the angle and the orientation type, and we can take that information and log it out to the browser. So as I save the changes, when we look over in the console, you don’t see anything show up.

SITK- Pie Shop - demo events - adding listener to orientationchange event

Remember that we have the mobile emulator available within the browser developer tools, and I can switch over to that. You’ll notice that as I switched over to the mobile view, it fired this event. Expanding the window out to make it a little bit easier to see, if I click on this button for Rotate, you’ll notice that as the event fires, the type goes from portrait primary to landscape primary 0 degrees to 90 degrees.

Now, there is a wide array of available events as you build your web apps, and we’ll be using a number of them as we finish up the implementation for Bethany’s Pie Shop in the next post. But next, let’s get a feel for what type of APIs are available directly within the browser.

Native API

API stands for Application Programming Interface. Now that’s just a fancy way of saying that there’s some code that you can use to work directly with the browser’s functionality. Putting it another way, using the browser’s API, you can control the features and the behaviour of a web browser. The best way to get an overall look at what APIs are available is to go over to the MDN web docs, and we’ll bring up the web API page that lists all the built‑in functionality of a web browser.

SITK- Pie Shop - native apis - MDN web docs

Now, by looking around on this page, you’ll be able to see that there’s a vast array of functionality that you can tap into. Want to draw something on the page?

SITK- Pie Shop - native apis - canvas

Want to request an additional file from the server? Fetch does that.

SITK- Pie Shop - native apis - fetch

Want to create drag‑and‑drop interaction on your page? Well, it is called HTML Drag and Drop API.

SITK- Pie Shop - native apis - HTML Drag and Drop

What about saving data in the database? The tragically named IndexedDB can do that for you.

SITK- Pie Shop - native apis - IndexedDB

And the list goes on and on. But there’s one problem. Not all of these APIs are available in all browsers. How do you know what you can use and whether or not there are alternatives if something you need isn’t available? Well, I’ll tell you right now, options do exist, and we’ll discuss those next.

Fallbacks and Polyfills

Sometimes the API you want to use isn’t fully supported by browsers, and we’ll look at how to determine browser support next. But for now, I want to introduce a few terms regarding API support. In situations where API support is inconsistent, there are two types of scripts that you can include on your pages that help compensate for the missing feature.

SITK- Pie Shop - api absense - fallback

A fallback is a script that your browser can fall back to if the built‑in functionality doesn’t exist. The fallback often doesn’t do as much as what the native API is supposed to do, but they exist as an alternative to built‑in browser functionality.

SITK- Pie Shop - api absense - polyfill

On the other hand, a polyfill is meant to mimic built‑in browser functionality by already using supported features. The main benefit here is that a polyfill is specifically built to have the functions, objects, properties, and behaviour that work the same way the built‑in browser functionality is supposed to work.

This way, once browsers fully support the API, you should remove the polyfill, and everything should work. Now that’s the promise. But be warned, you should still do extensive testing before you make changes like that.

Now that you’re familiar with fallbacks and polyfills let’s look at a few tools that can help you determine whether an API is supported well enough for your application.

Browser Support

Determining browser support is crucial because you need to know that the code you write will work with the web browsers accessing your site. Now, there are a couple of tools that you can use to help make these decisions. The first one is HTML5 Please. This website lists different native APIs and gives you some hints on how well they’re supported and what to do if they’re not.

SITK- Pie Shop - browser support - html5 please

In conjunction, is an excellent resource that brings you a broad spectrum of statistics regarding how well APIs are supported on different browsers. You saw a little bit when we talked about CSS, and we’ll use it a bit more here.

SITK- Pie Shop - browser support - caniuse

So we’ll take a look at a couple of different APIs here within HTML5 Please so you can get an idea of what this website offers. First, let’s take a look at the API of local storage. This is a built‑in API that allows you to store information within a web browser. You’ll notice that HTML5 Please has marked localStorage as use. So this is a fully supported API, meaning that you can use it with high confidence in just about any web application.

SITK- Pie Shop - browser support - html5 please - localStorage

As we look at the bottom, you’ll notice a link down here that says View browser share %. When we click on that, that brings us to directly to the section on localStorage. Here we get an idea of browser support and any extra resources that are available for this API.

SITK- Pie Shop - browser support - caniuse - localStorage

Now, localStorage is an extensively well‑supported API, so let’s look at something a little different. Currently, Web Workers are marked as used but with a fallback. So the advice here is that there may be a small percentage of web browsers that don’t support the API, and it gives you some ideas of how to work around that if you need to have 100% browser capability.

SITK- Pie Shop - browser support - html5 please - web workers

All right, let’s look at IndexedDB. This API is marked as caution with a fallback. So here it gives you some recommended polyfills, IDBWrapper and the IndexedDB Polyfill.

SITK- Pie Shop - browser support - html5 please - indexedDB

When we go over to for IndexedDB, scrolling down to the Resources tab, you’ll notice that it has links for polyfills and detailed information about places where there might be some deficiencies in the implementation. But you’ll see from the chart here, almost every modern web browser supports IndexedDB.

SITK- Pie Shop - browser support - caniuse - indexedDB

All right, let’s look at one last example. The WebSQL API is marked as to avoid. It is a deprecated API, and you don’t want to use this API unless you have a particular reason. And the advantage here is that the website gives us all of that knowledge ahead of time without having you figure that out the hard way.

SITK- Pie Shop - browser support - html5 please - WebSQL

Next up, we have the last post in this series where I’ll demonstrate to you how to update the rest of Bethany’s website to collect user data and send it to the server. And this is where it gets exciting because now we get to put into practice all the knowledge that you’ve learned about JavaScript to update the website to make it truly interactive.

If you need any help or something is going wrong, let me know. It will be my pleasure to help you. If you want to extend some point, we have discussed, contact me so we can cover in the fllowing posts.

We also have pro bono projects just in case you are interested in learning more about them.

Be aware of why we started this project by clicking here.

Learn more about other posts here.

Contact us for any suggestions. And follow us on FacebookInstagram and Twitter.

If you are a good reader like myself, I recommend the following readings:

  • Docker Quick Start Guide: Learn Docker like a boss, and finally own your applications
    • Docker for Developers: Develop and run your application with Docker containers using DevOps tools for continuous delivery
    • Responsive Web Design with HTML5 and CSS: Develop future-proof responsive websites using the latest HTML5 and CSS techniques, 3rd Edition
    • JavaScript: The Definitive Guide: Master the World’s Most-Used Programming Language 7th Edition

    See you in the next post!

    SITK - Pie Shop JavaScript 5of7 Featured image

    Exciting Web Development Journey – Pie Shop Website 5/7


    Welcome back to Sharing Is The Key. Let’s continue e introduction to Javascript. As we told you in the forth post JavaScript is the language of the web and one of the most commonly used programming languages in the Software Development industry, according to Stack Overflow 2020 survey. It is nearly used by 70% of professional developers.

    In the previous post we’ve learned about Strings, Numbers, Variables and we used the browser developer tools to better understand some JavaScript nuances. We’ll continue taking a look at the plus sign and the equal sign and the role and purpose of operators in JavaScript and much more.


    When you think of the plus sign, chances are the first thing that comes to mind is math, 1 + 1 is 2, and that’s precisely the result that we get from the browser. But what if we tried to use the plus sign with a string? If we type "John" + "Smith" what we get is a new string where the first and second ones are stuck together. In programming terms, we call this being stuck together concatenation. So “John” and “Smith” are concatenated together to make a new string.

    SITK- Pie Shop - Javascript - operators with numbers and strings

    Now, usually, I’d add a space between my first name and last name. So I have a couple of options. I could type + and then a space inside quotes, creating a new string that displays my name correctly. But I can also type my name with space and then + “Smith” which results in the same value.

    SITK- Pie Shop - Javascript - adding spaces between strings

    Let’s turn back to numbers again for a second. What do you think would be the browser’s response if I type an equation, including the answer? In other words, if I type in 1 + 1 = 2. What do you think the browser will say?

    SITK- Pie Shop - Javascript - show erro during numbers operation with equal sign

    Well, we get an error, and that seems somewhat weird, right? That’s because when you’re in JavaScript when you use a single equal sign, you’re telling the interpreter to set a value equal to something. Just like when you create variables when you type let x = 1, the single equal sign tells the browser that the variable named x will point to the value 1 in memory.

    SITK- Pie Shop - Javascript - assign variable x to a number

    Therefore, with an expression like 1 + 1 = 2, the interpreter is trying to set 1 + 1 equal to 2, and you can’t change the inherent value of what the expression of 1 + 1 is. It just doesn’t work that way.

    To get around situations like this, many programming languages, including JavaScript, use multiple equal signs to denote equality rather than assignment. I mean that if we change our expression to read, 1 + 1 === 2 with three equal signs, now we get back what’s called a Boolean value. Boolean means it’s either true or false. And 1 + 1 indeed does equal 2, so the value returned from this expression is true.

    SITK- Pie Shop - Javascript - numeric expression with 3 equal sign

    So there are several different operators available in JavaScript. In this course, we’ll use the plus sign to do some concatenation and the equal sign to assign values. And, of course, the triple equals to evaluate whether or not an expression is true.

    Knowing this now, we can use the power of the equal sign to start making our code seem like it’s making some decisions for us and using expressions to help provide control on how our code is executed.

    Control Flow: Blocks

    Now when we talk about control flow within the program, we’re referring to how the program executes and reads each line of code. Now sometimes, it doesn’t consistently run every line of code. Sometimes it skips some of those lines. And in doing that, that often gives the illusion that our program is thinking or making decisions. Now programs are built up of a fundamental building block of code called a block.

    Let’s take a look at an elementary block first. So down here, I’ve created a variable and called it name and set it equal to "John". Now notice right at the end of the first line, there’s that semicolon. That’s called a line terminator. And that’s what tells JavaScript or the interpreter that this is a complete statement. So blocks are made up of a series of statements or expressions. Now down here, I’m using the browser’s console to print up the value of the variable. If I save the page, you can see that John is printed in the console over here.

    SITK- Pie Shop - Javascript - console log John

    Now let me show you something interesting about the name variable. If I declare it again but give it a different value, what do you think will happen? So here I’ve added another name variable, this time set it equal to "Smith". And so when I save the page, let’s see what happens. We get an error because the identifier of name for our variable has already been taken. And it’s already been taken because these two variables live within the same block. They’re within the same scope in the same block.

    SITK- Pie Shop - Javascript - declare the same variable twice and get an error

    So, interestingly, what we can do is create separate blocks and then watch what happens. I’ve used the curly brackets to create a block around these two lines. And then the first name declaration is outside that block. So when I press Save, will it show up with an error, print up John, or print up Smith? Well, let’s find out.

    SITK- Pie Shop - Javascript - variable name with Smith in a block

    Since I declared the variables using the let keyword, it gives that variable a block scope. So it’s completely unaware of the variable that’s declared above it because that variable is only valid within this scope. So what do you think will happen if I move the console.log statement outside of that block? Now when I press Save, you got it, it prints up John.

    SITK- Pie Shop - Javascript - placing console log outside the block

    So blocks group statements together and affect how variables are used. Now let’s see how a block is used inside an if statement or a conditional statement.

    Control Flow: If Statements

    Now let’s add a little bit of interactivity to the program. Let’s allow our program to make some decisions. We’ll do that with an if statement. This if statement, also known as a conditional, is set up to use the if keyword. Then you put an expression between parentheses. After the parentheses, you create a block, so in the open curly brace, you have your statements within that block, and then you close it with a curly brace.

    SITK- Pie Shop - Javascript - explaining if statement

    Now our expression here is a little bit unique. So, where the single equal sign is used to set a value equal to a variable, if you want to evaluate a variable to determine what value it has, you use three equal signs. Now, in JavaScript, you have a little bit of choice here. You can use three equal signs, or you can use two equal signs. Two equal signs will work, but JavaScript has some interesting behaviour about how it evaluates whether things are equal when using two equal signs. It is called type coercion; it’s out of scope for our discussion here, so I’m just going to suggest using the three equal signs unless you know why you don’t want to use them. The three equal signs do exactly what you might think. You want to find out whether or not the name is equal to the string of “John”. By doing that, we’re creating this if statement, and if it evaluates as true, it’ll run the code that’s in the block underneath it. So let’s save the file and see what shows up in the browser’s console.

    SITK- Pie Shop - Javascript - explaining if statement - result

    And, of course, it says “Hi John”. So what would happen if I changed the value of the name variable to “Smith”? When I save that change, nothing’s printed on the console because we haven’t told it to do anything if the name doesn’t equal “John”.

    SITK- Pie Shop - Javascript - explaining if statement - does not enter if block

    So let’s add that portion to our conditional statement. So now, in addition to the if keyword, we have the else keyword. What else does is it gives us a block of code that can run when the original expression does not evaluate to true. Basically, this says, if the name variable does not equal “John”, then print this string on the console. So let’s save this change, and now we get our new message.

    SITK- Pie Shop - Javascript - explaining else statement

    And if we go back and change name to equal “John” again, save that change, you can see that it goes back to saying “Hi John”.

    SITK- Pie Shop - Javascript - saying back hi to John again

    Now you can take control of this even more. You can add as many if statements as you want and create a nesting. So if the first expression doesn’t evaluate as true, you can drop down to the next one and so on until it just goes into the else statement as we see here. Let me give you an example.

    So now, instead of just a single if statement, I have else if. This says in English that if the variable of name equals “John”, then say “Hi John”. But if it is “Paul”, says “Paul, is that you?”. And if it doesn’t say any of those, then say “Wait, where is John?”. So we can change the variable, set that to “Paul”, and there we have our message “Paul, is that you?” printed up in the console.

    SITK- Pie Shop - Javascript - explaining else if statement

    But if it’s a different name, then we get our default message of “Wait, where is John?” So by understanding the concepts of control flow and blocks, you can add a lot of interactivity to your programs. And so we’ve been using this little thing called log. This is actually a function, so in the next section we’ll talk about how you can create your own functions and how they all work.

    Declaring Functions

    This code works great here, but what if we want to use that greeting logic repeatedly in different places within a more extensive program? We could copy this code and place it in other spots within the program, but that creates a problem. If the logic changes or we find out we have a bug in our existing code, we need to change that in two spots. And trust me, I can tell you from experience; there are times when you will forget to update things in more than one location.

    So we always want to try and not repeat ourselves when we’re writing code. One of the best ways to do that is to wrap up blocks of code like this inside a function. So to illustrate, let’s change the code just a little bit at a time so you can see how a function works. First, what we’ll do is wrap it inside a function declaration.

    SITK- Pie Shop - Javascript - function declaration

    Now what I did is added the function keyword and gave our function a name. So here I called this greet. Then I’ve added the open and closed parentheses and then opened up a new block for my function by adding an open curly brace. Then at the end of the block of statements for my function, I added a closed curly brace and then indented the code in a little bit to make it easier to read. A convention within JavaScript is to indent code inside different blocks. So you’ll notice that the code’s indented for my function, and then it’s indented a little bit more inside my if blocks. It tells the browser that I now have something called greet, which we can run repeatedly. It creates a container around these blocks of code.

    Even though I already saved the file, you’ll notice nothing happened over here on the console. And that’s because this only declares the function. Now what we need to do is call the function. The way you call it is using its name, type the open and closed parentheses, and if it’s at the end of a statement, we’ll go ahead and add a semicolon. So what do you think will happen as I save the file?

    SITK- Pie Shop - Javascript - calling a function

    That’s right, it says Hi John.

    So the same logic that was run before is now run when we call the greet function. So if I call it again, you could see that the same code is run two times and I get the same result twice.

    SITK- Pie Shop - Javascript - calling the greet function twice

    Now, as my application grows, if I want to use the greet logic, I can call this function from anywhere within the program, and the same lines of code will run each time I call the function. Now, this is a great start, but we can make this much more flexible. Next, we’ll look at being able to declare arguments to pass data into our function.

    Passing Data into a Function

    Now, it’s nice that all this logic is wrapped up for us, but it’s still pretty limited. We have this block of code that changes what will be logged out to the browser according to the name variable’s value, but there’s no real way to change it at this point. We can add an argument to our function so we can pass the value into the function.

    Instead of declaring the name variable here inside the function, we can move it up into the function declaration. And now that that variable is declared within the function declaration, we can delete it from inside it. Now we have a function that wraps up the logic of looking at the name variable, and now we can pass in different values for the name as we call the function. So down here in greet, I can greet the first time I run it based on the name “John.” The second time I run it, I can run the same logic based on the value for “Paul.” And I can even run it a third time based on the name “Scott.” So now, when I save the file, what do you think will happen?

    SITK- Pie Shop - Javascript - calling the greet function with params

    When the greet function is run and the value of “John” is passed in from the name variable, we get “Hi John” When “Paul” is passed in for the name, we get “Paul, is that you?” And for “Scott”, we get “Wait, where is John?”

    By adding an argument to the function, it makes it much more flexible because now we can pass in data from the outside world and run the same logic against different values. And where things get interesting is instead of passing in hard‑coded strings to the function, we pass in variables. Instead of doing this, we could say, let name = "John", and now we can pass in the name variable into the function, and there we get our greeting.

    SITK- Pie Shop - Javascript - calling the greet function with params via varible

    So within the application, as the name variable changes, we get the expected result.

    SITK- Pie Shop - Javascript - calling the greet function with params via varible - Paul example

    Returning Data from a Function

    Now that you’ve seen how to pass data into a function, let’s find out how you can get data out of a function. So I’ve simplified our greet function here and taken out all the logic just so that we can hone in on what it means to return data out of the function. To do that, we use the return keyword, and whatever follows the return keyword is what comes out of the function when you call it. So here, to keep things simple, I’ll add in the string “Hello.” So now, when I call the greet function, when I save it, nothing happens.

    SITK- Pie Shop - Javascript - returnind data from a function - first action

    And the reason nothing happens is that all we’re doing in line 62 is calling the greet function, but it is now returning a value, so we need to do something with it. Instead of just calling it, let’s take what comes out of the function and set that equal to a variable.

    SITK- Pie Shop - Javascript - assigning a funtion return to a variable

    So this line says, let the message variable be equal to whatever value returns as a result of running the greet function. So when we run this, the string “Hello” is set equal to the message variable. We can now log out the contents of the message, and as I save the file, you can see that “Hello” is printed up on the screen.

    SITK- Pie Shop - Javascript - console log the return from a function

    Now we have the same issue here. We don’t want to hardcode the return value of our function necessarily, so we could return the name variable as it’s passed into the function. Let’s consider “Mary” coming into the greet function. It sets the return value to the message variable, and then when console.log runs to print it out in the browser.

    SITK- Pie Shop - Javascript - console log the return from a function with no hardcode

    Let’s introduce our logic back into the function, and then you can see how powerful this can be. So here, the function is updated with our greeting logic again, with some exciting variations. Now, starting from the top, you’ll notice that I declared a variable named result. Now, this is a practice that I like to do anytime I’m creating a function that has to return a result. It’s always best to declare it at the top and give it a default value. Here I’m going with an empty string. Based on the if statements within my function, I know that the variable will get a new value, so I could start with an empty string, but then the last statement will return the result.

    SITK- Pie Shop - Javascript - function explained in details

    Now within my if blocks, instead of just calling console.log based on the generated message, I’m setting results equal to those strings. So if the variable name equals “John,” the result gets the value of “Hi John” Just like if name equals “Paul,” the result variable receives the value of “Paul, is that you?” It is mighty because it opens up this logic, not just to console.log. I could use the same greet function to log the result out to the console, yes, and print it up on the screen or use it in any other way within my program. So now, as I come down and call the greet function, I can pass in “John,” I get the result of that logic being returned out of the function, and then I can take that result set into the message variable and do whatever I want with it. In this case, console.log. But here we’re dealing with what’s called in programming the Separation of Concerns. Let’s save it and see, we’ve got Hi John.

    SITK- Pie Shop - Javascript - function explained in details - separarion of concerns

    The greet function is only concerned about creating a greeting based on a name that comes in and nothing else. And to verify you can see it working, that’s with “Paul” we get the expected result.

    SITK- Pie Shop - Javascript - get expected result with argument Paul

    Object Literals

    Next, let’s talk about object literals in JavaScript. Now the notion of objects and what’s called object‑oriented programming is a vast subject. And when it comes to JavaScript, there’s a lot of different nuances in how the language deals with objects. While all these concepts are powerful and essential, for our purposes here, we’re going to ease into the discussion of objects by looking at what is called object literals. Now one way to think about an object literal is that it groups data and functionality. So let’s consider a couple of different related variables.

    SITK- Pie Shop - Javascript - object literals - declaring 3 related variables

    So I can take this same information and group it together. As I look at this information, it all relates to me, and I’m a person, so I’ll create a new variable and call that person. And what I’ll set that equal to is open and close curly braces. It tells JavaScript that the person variable is going to be an object literal. If you recall from earlier discussions, it creates a block for us, so inside this block, I can create properties for my object. Now I’ll start the first name property from my object, and instead of setting it equal to its value by using the equal sign, here I use a colon. And while since we’re at the end of the line, you might think we need a semicolon, as we declare object literal properties, we’ll use a comma instead. Now I can create my last name and finally my Twitter handle.

    SITK- Pie Shop - Javascript - object literals - creating person object

    It becomes exciting because instead of dealing with the individual pieces of data for firstName, lastName, and twitter, I can use just the person object. So when I pass person into console.log, and we look at the browser console, you can see that it logs out an object to the console. And when I expand out the object there, I have individual properties for firstName, lastName, and twitter.

    SITK- Pie Shop - Javascript - object literals - console log person object

    So what that means, if I want to target specific pieces of data within that object, I can use dot notation, so that would be person dot, and then I can access the firstName, lastName and twitter properties. And if you notice something cool, I also have statement completion within Visual Studio Code. So when I press that dot, it’ll show you the different properties associated with that object.

    And it becomes even more interesting when we add some behaviour together with this data. So you remember our greet function from before? Well, we can add that in here as well. This time, instead of declaring a string, I can declare this property as a function. And inside the function, I can log out my greeting. And here I’ll say “My name is John”. Now inside the function, I have access to the properties of this object by using the this keyword. There’s a lot that goes on in JavaScript with the this keyword, but we’ll be able to use it here within this function for right now. So now I can come over and call that function directly off of my object. So when person.greet() is run, I get the message of “My name is John”.

    SITK- Pie Shop - Javascript - object literals - calling object methods

    So as we implement Bethany’s Pie Shops, you’ll see objects a lot, especially when we call functions of other objects, just like you’re used to seeing under console.log. Sometimes, we have lists of data that we want to use all at one time, and so next, we’ll look at arrays in JavaScript.


    When was the last time you went to the grocery store? And when you went, what did you take with you? Chances are, you probably had a shopping list, and that list probably included a wide array of items that you needed to buy at the store, everything from milk to eggs to bread and flour. Now, in JavaScript, an array is just that. It’s a list of values.

    So let’s take a look at this working here in the browser. Now, the way you declare an array or the way you create a list declares a variable and sets it equal to open and closed square brackets. This bracket notation is what tells the browser that you’re declaring a list or an array. So, let’s start working with a series of numbers. We can fill this list out by adding in values with commas between them. When we log the array out to the console, you can see that it shows us this list. I can expand the list; we can see the individual values within the array.

    SITK- Pie Shop - Javascript - array - console log an array

    Arrays are pretty flexible. It doesn’t have to just work with numbers. In fact, you can do strings as well. So here I’ve created a list of names, and so when we save that, you can see that the array shows up with that same list of names.

    SITK- Pie Shop - Javascript - array - console log an array of strings

    But you can also mix different types of data within an array. In this example, I have a number, a Boolean value, and a string. And when we look at the result in the browser, you can see that the same values show up in their places inside that list, all being different types of data inside the array.

    SITK- Pie Shop - Javascript - array - console log an array of different types

    As you take a look at this list, you’ll notice some numbers associated with each value. Here, for the first one, it has 0, and then we have 1, and then 2. It means arrays are zero-indexed.

    Now, I know that doesn’t make sense, so let me show you what I mean here. Right now, I’m passing the array variable into console.log. But if I want to access the first value in the array, I can use the open and closed brackets and then pass in the index or value. So if I want 100, I can pass in 0, and now when I save that, it just returns the value for 100.

    But once we have that array, once we have that list of values, there are all kinds of neat things that we can do with it. We can take those values and reverse them.

    We can get the count of the items in the array, which in JavaScript uses the array’s length property.

    And you can even add and remove items from the array. So if I wanted to add something to this list, I could call the push function, and so it returns for me the new length of the array, but I can also ask for it again. And there, I get the count of the items that are inside the array.

    SITK- Pie Shop - Javascript - array - adding item to the array

    So what’s powerful about arrays is you have this list of data, and then inside your program, you can access each one at a time and do something interesting with them. But to do that, we need to use a loop, so we’ll look at loops next.

    While Loop

    Have you ever heard the joke about how the guy got trapped in the shower? He was looking at the instructions on the shampoo bottle, and it read, you wash, rinse, repeat. Yeah, he never made it out. This set of instructions created a never-ending loop, and loops are powerful constructs for a programming language. They allow you to do what we call iterate or do something over and over again, and in context with our last discussion on arrays, you can iterate over lists of data as well.

    Let’s start out simple and see what it looks like to work with your first loop. Now to use our loop we’ll implement some logic that does some counting for us. So let’s say we want some code that will count from 0 to 10. Well, we’ll start off by creating a couple variables to give us the starting point and the ending point.

    SITK- Pie Shop - Javascript - array - declaring count and max variables

    Now when we think about what we want to do in terms of everyday English language, we want to keep counting while the value of your current count is less than the maximum. So you’ll count from 0, 1, 2, 3, 4, all the way up to 10, and you’ll do that while the current count is less than the max. In terms of JavaScript syntax, there’s a keyword called while, which we can use to create this loop. While it takes an expression, and as long as it returns true, it will keep executing the block that is underneath the keyword. So we want it to keep processing while the count is less than the max. As it runs, we want it to print out the current count, and then to make sure we don’t get stuck in the shower or inside an infinite loop, we need to make sure to increment the counter. So when we get to the end of this block, we want the count to equal whatever the count is, plus one more. When we save the file, you can see that it uses a loop to count from 0 to 9.

    SITK- Pie Shop - Javascript - loop - while

    Now, if you recall from our conversation about arrays that are indexed at 0, this is doing the same thing. Our count starts with the value of 0. The block inside the loop executes ten times, so starting from 0, we go all the way to 9 by implementing the count by 1, 10 different times. While loops allow you to create a loop that repeats the exact instructions while an expression is true.

    While loops are useful, you don’t see them as often as another type of loop, and that’s the for loop. We’ll look at that next.

    For Loop

    Picking up where we left off with the while loop, I’d like to show you another loop called the for loop. Now the for loop is a little more cryptic, and that’s because the syntax is a bit more compact, but the way it’s set up gives you a lot more flexibility in how you can work with objects and data inside the loop.

    Here, let me show you what I mean. We declare variables outside the loop and manage the count’s value at the bottom of the loop with our while loop.

    SITK- Pie Shop - Javascript - loop - while

    Let me paste in a for loop and you can see that the syntax is different, but it still prints out the same result to the console window.

    SITK- Pie Shop - Javascript - loop - for loop

    As we look at the anatomy of this loop, you’ll begin to recognize some of the same types of constructs present in the while loop. So first, we have our counter. Usually, you’ll see for loops use a variable name of i, to begin with. It generally stands for indexer or the index value of the loop. So it starts with an initial value of 0 for i.

    SITK- Pie Shop - Javascript - loop - for loop initializationi of i

    Now the loop continues to iterate while the value of i is less than 10. As we’ve seen before with our while loop, we had a variable called max, and here, we’re just setting the maximum value explicitly to 10.

    SITK- Pie Shop - Javascript - loop - testing max value

    Now, each time the loop executes before it reruns the block, it increments the value of i. It is a new notation and is shorthand for saying i = i + 1.

    SITK- Pie Shop - Javascript - loop - increments i by 1

    Once again, the loop is initialized with a variable named i, its default value is set to 0, it continues to run while the value of i is less than 10, and every time it runs, it increments the value of i by 1. So now, this loop is much more compact, and the indexer is readily available to us.

    So how might we use a loop like this? Well, let’s take an array of numbers and see what that looks like. So this time, instead of telling the loop that we want it to run while i is less than 10, rather what we’ll do is have it look at the length of our numbers array.

    SITK- Pie Shop - Javascript - loop - iteratinover numbers array with for loop

    We can now use the double bracket notation to pass the index value into our array to get the individual value from the list.

    SITK- Pie Shop - Javascript - loop - console log each numbers item

    Again, as this loop executes, i is initialized to 0, it will continue running as long as i is less than the length of our array, and in this case, that’s 3, and then each time it runs, the indexer or the i value is incremented by 1. Each time it runs, we can use the value of i to extract the number of the appropriate position.

    So I’ll save the file, and here within the browser’s console window, you could see that it prints up 1, 2, and 3, and of course, that works on any array.

    SITK- Pie Shop - Javascript - loop - iteration over numbers array - result

    Now arrays have a function that makes working with loops even easier for array values, and that’s called for each, and we’ll look at that next.

    forEach Loop

    Now JavaScript arrays feature a convenient function called forEach, and what it lets you iterate over the values of an array one by one. But the syntax is so much more straightforward than a for loop and a while loop.

    So here I have an array of day names, and so if I want to print something up for each one of those, I can start by calling the function forEach off of the day’s array.

    SITK- Pie Shop - Javascript - loop - starting array foreach function call

    Now, this function takes a function. It is a feature inside of JavaScript where a function can automatically call another function. So inside this function, we’ll create a new function, and you’ll notice that we’re not giving it a name. So this is called an anonymous function. Now forEach is going to pass some values as arguments into my anonymous function. The first thing will be the data for each item on the list, so we’ll give this argument the name of the day. It also passes in the index value of the item within the array.

    SITK- Pie Shop - Javascript - loop - filling in the function inside forEach function

    It is really handy, so we’re not left guessing what position in the array the value that comes in is within the array. So now we can use this to print up some information within the console window of the browser. So we’ll do console.log. And now I’ll show you something new when you’re working with strings. Instead of just using quotation marks, I’ll use the backtick character. Now, this creates a template string that allows us to do something exciting. Here I want to print what the day is, so I’ll do day: space, and now I want to get the value of the day variable and stick it into my string. I can do that simply by putting in the dollar sign and opening and closing curly brackets and then putting day right in there. I also want to show the index value, so I can do the same thing by grabbing the value of the variable index and placing it inside my string.

    SITK- Pie Shop - Javascript - loop - building up console log using template string

    So as I save the file, you can see them over here on the console. I’ve got Monday at index 0, Tuesday at index 1, and Wednesday at index 2.

    SITK- Pie Shop - Javascript - loop - building up console log using template string - result

    Well, congratulations, you’ve come a long way learning about the basics of JavaScript. In the next post, we’ll push things a little further and show you how you can begin creating interactivity with JavaScript in your website.

    If you need any help or something is going wrong, let me know. It will be my pleasure to help you. If you want to extend some point, we have discussed, contact me so we can cover in the fllowing posts.

    We also have pro bono projects just in case you are interested in learning more about them.

    Be aware of why we started this project by clicking here.

    Learn more about other posts here.

    Contact us for any suggestions. And follow us on FacebookInstagram and Twitter.

    If you are a good reader like myself, I recommend the following readings:

    • Docker Quick Start Guide: Learn Docker like a boss, and finally own your applications
    • Docker for Developers: Develop and run your application with Docker containers using DevOps tools for continuous delivery
    • Responsive Web Design with HTML5 and CSS: Develop future-proof responsive websites using the latest HTML5 and CSS techniques, 3rd Edition
    • JavaScript: The Definitive Guide: Master the World’s Most-Used Programming Language 7th Edition

    See you in the next post!

    SITK - Pie Shop 4of7 Featured image

    Exciting Web Development Journey – Pie Shop Website 4/7


    Welcome back to Sharing Is The Key. Let’s continue styling Bethany’s Pie shop website. As we have seen in the third post CSS is really powerful when it comes to providing an outstanding look and feel and having complete control of all HTML elements flow.

    Let’s look at building up the styles for the main content area of the page. Now the styles for the main element will give us our background for the page and enforce some base dimensions for us.

    I’ll add a tag selector for the main element and tell the browser to display this as a block‑level element. Now to add in a background image, we can use the background‑image rule. Now, rather than just adding a string here, we need to use the URL modifier to tell the browser to interpret the path we give it to an image. So inside the parentheses, we can add in that path within quotes. So here we’re looking for images/background.png. When I save the style sheet, you can see that that background image shows up all across the page because all the content inside the main element is filling up the page, and that background image is set automatically to repeat itself. So as this page grows and shrinks, the background image will take up the same amount of space as the main element.

    SITK- Pie Shop main background image

    Let’s add some padding, and we’ll do that to the top and the bottom of the main element. I’ll use explicit rules instead of the shortcut, which I showed you for the margin up on line 43. And this is to show you the different ways that you can write the style rules. So here for padding‑top, I can tell it that I want the padding to be 3em, and padding‑bottom, the same. We want to have the content push away from the boundary of the main element to give space for those navigation elements to show up correctly. And the last rule that we’ll add in is min‑height set at 85%. This rule is necessary to ensure that the bottom navigation shows up at the bottom of the page. When I save the file, you can see that the elements readjusted a little bit on the page. We’re not able to see much of the difference at this point. Mostly, it’s that background image that’s being loaded in for us. But as we flush out the style sheet and test it under different dimensions, then you can see how these rules are relevant.

    SITK- Pie Shop main padding top and bottom and min height

    Global Styles: Footer, Aside, and Article Rules

    So as we scroll down on the page, you can see that our footer is looking a little squished within its container. So let’s add a rule in order to give some padding around that container so that those links have some area to breathe.

    I’ll add 15px of padding around the entire div element. Let’s save it. See, that’s much better.

    SITK- Pie Shop adding padding to the footer

    For the content inside the middle, which means the aside and article elements, we’ll give it a padding of 2em.

    SITK- Pie Shop adding padding to aside and article

    So when I save the page, you can see that now there’s more padding around its content. Now, the em unit gives you a chance to create a size based on the current font size. Instead of hard‑coding pixels, depending on how the fonts are rendered within that container, if you zoom in or zoom out, the em unit of measure takes that into account. So, pixels are a fixed value, and ems are a proportional value. Another way of saying that is the larger my fonts are within my page, the more padding there will be around it, and the smaller the fonts, the less padding there will be.

    And this is important to create flexible layouts because as the dimensions change within your page, you want certain portions of it to reflect that.

    Now, we want our site logo to show up centred on the page to add a style for that. So inside the aside element, we’ll say text‑align: center. So I’ll save the page, and you can see that now it’s centred.

    SITK- Pie Shop centering logo on the page

    Now, a couple of different things are going on here. Number one, it says text‑align, and I just centred an image, and that might seem a little strange, and it is. But if you want to center an image or text within a container, this is the rule that you use. What’s nice about using this type of approach, when the page is rendered for a mobile device, the elements stack together under a narrow layout. The aside element will take up the full width of the page.

    However, and let’s take a look at the finished layout for a moment one more time, when the layout is rendered for the desktop dimensions, the aside element only takes up a portion of the page because of the grid layout that we will implement coming up soon. So this creates a lot of flexibility for you. So the layout looks good under mobile contexts, as well as desktop contexts.

    SITK - Pie Shop - Home Page

    But for now, the logo is just centred on the page, and that works great when we’re working with really narrow viewports, like mobile devices. Now let’s add one more style rule for our article, and that’s to set the width of that element to 75%. Now, this rule makes sure that our content doesn’t stretch too far across the page. And if you remember, we’re doing mobile styles first. All the styles that we’ve done until now are created to be optimized for our mobile layout.

    SITK- Pie Shop article width to 75%

    Global Styles: Media Query

    Our Home page is coming along quite nicely, and we’ve been able to style everything on the Home page so far using global styles. I mean that all of the style rules we’ve added into the site.css file will apply to every page on our website. Up to this point, all the styles have been tailored to be optimized for the mobile environment, so now, let’s add a media query that gives us a place to put in some rules for styles that target the desktop experience.

    So the media query that we’ll use will give a minimum width and target it to the screen. So this media query targets the min‑width of 768px, so these styles will only be applied to screen sizes that are 768px wider and above.

    SITK- Pie Shop start media query to desktop experience

    So the first thing we want to do is for the main element to display as flex. Now the reason for this is because we’re going to create a two‑column layout, and if you remember from our discussion on layouts and columns, display: flex makes creating those layouts very simple.

    SITK- Pie Shop desktop experience - main display flex

    Next, we want the logo to pull away from the left side of the screen just a little bit. So I’m going to add some margin to our aside element, and we’ll give it a margin‑left of 2% of the total space available to the browser window.

    SITK- Pie Shop desktop experience - aside margin left 2%

    So we’ll save those changes, and then we’ll look at the browser in a desktop view. So there it is, now our desktop layout has a two‑column layout, and that logo is positioned exactly where we want it on the page for these dimensions.

    SITK- Pie Shop desktop experience - result

    Now we’re almost there. All we have to do now is add some page‑specific styles to make the Home page look exactly the way we want it. Again, everything we’ve done until now is some styles that apply to every page within the website. Now we’ll add some styles that are only for the Home page, so we’ll do that next.

    Home Page Styles

    Here we are, back in the markup file, the HTML file for the Home page, and we’re going to add some page‑specific styles here. We could do that in a style sheet that’s referenced out from the page, or we can do it inside a style element. To keep things simple, I’m going to use a style element here, but if you were building things for the real world, you’d probably want to use a separate style sheet.

    SITK- Pie Shop back to the index html page

    Now I noticed we don’t have the correct title on this page, so let’s go ahead and fix this up and title this Home page “Bethany’s Pie Shop” and save it.

    SITK- Pie Shop fixing home page title

    Let’s create a style element and add some page‑specific styles. One of the first things that we want to do is update the style of the welcome text. We need this text to be bigger and maybe change the margin a little bit. So we’ll target the h1 on the page and tell it we want the font-size of 3em, and what we’ll do is add some margin-top of 0.5em. It makes the text bigger and pulls the text away from the image just a little bit. Saving the file, you can see that now we have a proper welcome message.

    SITK- Pie Shop page-specific styles - h1 font size margin top

    This banner is a little bit of a problem because you’ll notice that it pushes off and seems to mess up the layout.

    SITK- Pie Shop page-specific styles - banner mess up layout

    Now we can fix that by telling the banner we only want it to have a max-width of 100%. So we’ll target the banner. If you remember down in the markup, we gave it a class name of banner. Now when I save it, you’ll notice that it brings that banner down into size.

    SITK- Pie Shop page-specific styles - fixing the banner layout messup

    And if I resize the browser, you can see how it scales.

    So that’s the value of creating styles with relative values or percentage values because they’re able to adapt or, as we say it, respond to the different layout needs. These are the techniques that you use to begin to create a responsive website.

    The text down at the bottom of the page does not look good. What we want to do is have it pop on the page a little bit, so we’ll add a background colour, change the font size, and adjust the padding just a little bit. Again, there’s a class name that we’ve created called sub‑title, and I’ll use a class selector to create my rule here. We’ll make the background colour white. So we’ll bump up the font size, give it a background colour, and give it some padding, so the text isn’t pushed right up to the edge of the container. And with that change, our Home page is done.

    SITK- Pie Shop page-specific styles - pop up welcome message

    So whether it’s on the desktop or a mobile device, our website is starting to take shape.

    With the Home page done, we can now turn our attention over to the Contact page, and we’ll do that next.

    Contact Page

    As we turn our attention to building the contact page, we’ll use the home page as a starting point. Here on index.html, I’ll select the entire contents of the page, copy it, come over to the contact page, and paste all of the code from the home page. So that gives me the foundation of the page and gives me the building blocks of the layout.

    SITK- Pie Shop contact page - copying from index

    I want to change the content in the middle of the page, so nearly everything inside the article element. So I can delete the contents out of the article, delete the page‑specific styles out of the contact page, and then update the title. Frequently websites will put the title of the page first, and then a pipe, that’s the vertical bar with spaces around it, and then after that, the name of the website itself. It works well for search engines because if the title shows up in the search results, you can see what page is being returned. So I’ll save all those changes.

    SITK- Pie Shop contact page - saving contact page changes

    And then we can come over and click on the Contact page, and you can see that we’ve got the basis for the layout, just none of the content yet.

    SITK- Pie Shop contact page - empty contact page

    We can now go down to the article element and add in the content for the contact page. I’ve pasted in the markup here, and it’s made up of an h1 that says it’s the “Contact” page, a text message that’s in a paragraph tag, and then this very long, interesting‑looking anchor. Now, before we talk about what that is, let’s save it and look at the page for a second.

    SITK- Pie Shop contact page - with content

    That anchor tag renders out a link. And so when you do that, if you have a default mail client set up on your machine as I do, it’ll bring up the mail program, it sets the To address to whatever you designate, and here for this demo, it’s I also automatically added in some text for the subject of the email. So here, “Interested in pies”.

    Now that you see what it does, let me show you how it does it, the anchor tag is set up to have an href value, but instead of just pointing to a web address, it starts by saying mailto. After that, you give the email address. After the email address, you put a question mark and then say subject=. It maps to the subject line in the email program, and then I can put in “Interested in pies”. But you’ll notice I’ve got this unique code in here, %20. That’s a particular type of code that tells the program to put a space inside the text. So here, Interested%20in%20pies. And so that code is what tells the email client how to construct the message. Then I can add in the rest of my label here, “Send us an email”, and close the anchor tag. After that, all I had to do was put the rest of the message underneath it. And that’s all enclosed in a paragraph tag, and that’s what gives us the contact page.

    Well, now that we’ve got a way for people to get hold of us, let’s build the pies list page so we can begin the foundation of starting to take orders.

    Pies List: Markup

    Again, using the finished product as our reference, I’m going to click on the Pies menu and get a list of available pies from the Home page. Now we’re going to build this page in two different stages. First, I’ll show you how to develop the page to display the pictures in this type of layout, and then next, we’ll begin talking about JavaScript, and after that discussion, we’ll add the interactivity to this page.

    SITK- Pie Shop - Pies List page

    Let’s go back and start building this page from the ground up. Returning to our Home page, we’re going to take the same approach with the Pies list page as we did with the Contact page and start by just copying what we have here, to begin with. So on index.html, I’ll select all, and then copy this code and put it inside the pies.html page. I’ll paste that in, and again, what we want to do is take out everything inside the article element, so I’ll select all this code and delete it. We’ll also get rid of the page‑specific styles for the Home page, update the title to say “Pies”, and then add in that pipe. So when I save it and now navigate to Pies, you can see we’ve got the basis of the layout ready for us to put content into.

    SITK- Pie Shop - empty pies page

    One of the first things that I want to do is create a new container inside the Pies list page. And so here I’ll make a section element and give it a class of columns‑desktop, and we’ll look at why that’s important here in a moment. The layout for our list page will be different on the desktop than it is for a mobile device, so by adding in this class, we’ll add some styles that will allow this page to work well on the desktop.

    SITK- Pie Shop - pies page - adding a section

    So now we can add in two different pies. I’ll add in the first one, which is an apple pie. Now each pie is going to take on a similar construction within HTML. First, there’s a container div that has a class of pie. It is essential because as we add more pies to the page. By creating a pie class, I can add styles to that class name and apply them to each one of the pies on the page.

    SITK- Pie Shop - pies page - pie div

    Well, we need an image for it, so here’s an image element for the thumbnail for our apple pie.

    SITK- Pie Shop - pies page - pie div with image

    Now, in this next container, I’m using the columns class. We will add the styles for this next, but this will allow the layout to position the price and the title next to each other in two columns.

    SITK- Pie Shop - pies page - pie div with title and price columns div

    Then we have our description and then the button we need to place an order for the pie.

    SITK- Pie Shop - pies page - pie div with description and button

    So I’ll save these changes, and let’s take a look at them in the browser. And the result is pretty bad. It doesn’t look good at all. It is alright because we’re going to fix that.

    Well, let’s go ahead and get our cherry pie in there, and then we can work on making this look better. Like the apple pie, the cherry pie is within a container with a pie class. There’s the thumbnail image, the title, the price, description, and then an order button.

    SITK- Pie Shop - pies page - cherry pie div

    And one thing we didn’t talk about a moment ago was this data‑order attribute. A data‑attribute is a special type of attribute that you can add into an element that allows you to add extra information about that element.

    SITK- Pie Shop - pies page - cherry pie div - data order attribute

    Now, when we create the interactive part of this page, to tell the order page what people have ordered, we’ll ask this button for its value of the data‑order attribute. So are you ready to take a look at what our page looks like now? Again, it’s not quite what we want, but that’s okay because next, we’ll add in the styles that we need for this page to look the way we want it.

    SITK- Pie Shop - pies page not styled yet

    Responsive Columns

    Taking a look at the final product one more time, this is the pies list page, and this one looks pretty nice.

    SITK- Pie Shop - Pies List page

    But the current state without any styles does not look as great.

    SITK- Pie Shop - pies page not styled yet - desktop

    Now, as we add these styles, we’ll be using the pie class to target the container and style the elements specifically for the pies on the page.

    SITK- Pie Shop - pies page - targeting pie class for styling

    And if you remember, the title and the price right now show stacked on top of each other, but we have them in a columns class, so we’re going to add some style first to make sure that these show up as columns.

    SITK- Pie Shop - pies page - targeting columns class for styling

    So when we switch back over to the style sheet, we’re going to want to scroll down the style sheet just before the media query. And so, right here in this position, we’ll add a style telling the browser to display columns as flex. When I save it, you can see the title and the price stack next to each other instead of on top of one another.

    SITK- Pie Shop - pies page - title and price next to each other

    We’ll add some more style rules in a moment to make it space out the way we want, but this is an excellent general style to have within the global style sheet. Any time we want to have columns, all we have to do is mark those elements like columns, and they’ll display as flex.

    Inside the media query, there’s another style that we want to add that’s specific to the desktop layout. If we look back at the HTML for a moment, inside the article, we have first the title and a section that includes the containers for both pies.

    SITK- Pie Shop - pies page - h1 title and a secion with both pies

    But that section has a class of columns‑desktop. Now the purpose of that is to show the pies stacked together in columns for a desktop layout, but they’ll be stacked one on top of another for mobile layouts.

    SITK- Pie Shop - pies page - section with columns-desktop class

    So let’s add the style to tell the desktop layout to stack these as columns. Inside the media query, we’ll add a rule right underneath the aside rule, and this is for the .columns‑desktop class. And again, the rule here is display: flex;. Now I just saved the page, and with the dimensions for a desktop browser, things will change slightly. So as you can see with that rule, now we have the columns stacking next to each other.

    SITK- Pie Shop - pies page - apply display flex to columns-desktop class

    Next, we’ll add the rest of the styles to make these pies look precisely how they should.

    Pies List: Styles

    Now, to start styling the containers for the pies, we’ll add some rules just outside the media query rules. Sometimes, as your style sheets grow, you might want to add some comments to help you organize the styles better. So here I’ll add a comment to signify that the following styles are just for the pies. Comments are lines of code that we can put in different programming languages entirely ignored by the computer. So here, the syntax for comment in CSS is /*, and then some text, and then */ to designate the end of a comment.

    SITK- Pie Shop - pies page - comments in CSS