Foundations

This week, you'll lay the foundations... of the foundations. Everyone has seen some web technologies before -- whether it's just as someone who's used websites, or built some of your own. These technologies are ubiquitous.

Whatever your prior expereince, this week you'll touch on HTML, CSS, and JavaScript, three core languages at the heart of the internet. As you get your first taste of reading and writing each language, you'll focus on how they are connected.

You'll also start practising learning and working together. The internet is social, and technologists build it together. So, that's what you'll learn to do too.

Learning Outcomes

After this week, you will be able to:

  • Explain the role of HTML, CSS, and JavaScript
  • Use core HTML elements to structure a webpage
  • Select and apply styles using CSS
  • Use a script tag to include a JavaScript file on a webpage

An overview of this week content

Web Development

This course is about how to build web pages.

Web Development is everything that’s involved in building websites. Websites as different as Youtube, Wikipedia, Twitter, and Google all use the same building blocks under the hood. Under the hood, all of those websites use HTML, CSS, and JavaScript.

All the familiar features like text, images, colors, input boxes, forms, and videos are made out of these technologies. There’s some features like chat or purchases that require learning more than what we’ll cover in this course, but everything you see on the web is based on these foundational languages.

In this course, you’ll learn the basics of building websites with HTML, CSS, and JavaScript.

HTML, CSS, and JavaScript

Web pages are built using different technologies. The most basic and fundamental ones are HTML, JavaScript, and CSS.

Roughly speaking,

  • HTML is for content
  • CSS is for styles
  • JavaScript is for interactions

These three languages come together to make up a website.

HTML - HyperText Markup Language

HTML makes up the content and structure of the webpage. It’s what a page is made of.

Here’s an example.

<p>
	This is a paragraph. It has an
	<a href="https://example.com">
		Example Link
	</a>
	inside the paragraph.
</p>
<img src="valley-waterfall.png" alt="this is an example image" />

HTML is text! The syntax uses the angle brackets <> to identify elements that make up a page. You'll learn lots of different elements.

CSS - Cascading Style Sheets

CSS controls the appearance of HTML elements.

CSS is made of rules that look like this:

p {
	color: red;
}

This CSS sets the color of the text within paragraphs to red.

Here’s the result:

paragraph with red text

Here’s the HTML content that's being styled:

<p>
	This is a paragraph. It has an <a href="https://example.com">Example Link</a> inside the paragraph.
</p>

JavaScript

JavaScript (often abbreviated JS) is a programming language that runs within the browser. It has many of the same features as other programming languages like Python, Ruby, or Java, but lots of quirks and specific details to learn about the language itself.

Here's a small example program in JavaScript that adds a list of names to the page:

let names = ["Lola", "Wasiu", "Rob"]

for (let name in names) {
	document.querySelector('.container') += name
}

In summary

  • Websites are made of HTML, CSS, and JavaScript
  • HTML has elements that look like
<a href="https://example.com">A Link Example</a>
  • CSS has rules that control the appearance of selected elements, like
p {
	color: red;
}
  • JS is a programming language like Python, but with some differences in syntax and what it can do

For the rest of the course, you'll dive deeper into these three languages, and get lots of practice reading and writing these languages to build webpages.

The Web and the Internet

The Internet

Even though we tend to use "the web" and "the internet" interchangably, they're actually two different things. While the focus of this course is on the web and web development, it's good to have some foundational understanding of the internet.

Starting in the 1960s, university and government researchers created a system to share files between computers. That system, called ARPANET, established protocols for file sharing, routing, and messaging that grew into the public internet.

Since then, the internet has grown to become a global network of cables, cell towers, satellites, phones, and computers, all connected by networking protocols descended from those of ARPANET.

You may have seen protocols like http (it's in the address bar, or at the beginning of a URL). Protocols like HTTP (the hypertext transfer protocol) are sets of rules that software programs follow so that they understand each other.

Connecting billions of different devices requires a lot of rules! There are a lot of protocols that make up the modern Internet -- HTTP, TCP/IP, Ethernet, DNS, Websockets... Even Bluetooth is a protocol that carries internet traffic!

You don't need to know what those acronyms stand for yet. You should know that the Internet is made of a lot of devices, connected by protocols.

Web Pages

If the Internet is the connections between the computers plus the protocols they use to communicate, the Web is the most visible way that people interact with the internet in their daily lives.

The Web was originally conceived as a collection of files and documents, shared and linked together using the internet.

Web pages are documents, created using HTML, CSS and other web technologies. Web pages can be accessed using a web browser, like Chrome or Edge. Pages contain text, images, links, and other elements.

A combination of multiple web pages makes up a website.

📺 How does the web work?

Here’s the main things to focus on:

  1. You use your browser to navigate to a url:

Navigating to a URL in the browser

  1. Your browser requests files from a server
  2. The server sends files
    • HTML
    • CSS
    • JavaScript
    • images
    • others like audio, fonts, and attachments
  3. Your browser turns those files into the page that you see.

A successfully rendered webpage, the Kibo homepage

Further Exploration: Clients and Servers

Computers connected to the web are called clients and servers. A simplified diagram of how they interact might look like this:

https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works/simple-client-server.png

  • Clients are internet-connected devices. For example, your computer connected to your Wi-Fi, or your phone connected to your mobile network, using software available on those devices — usually a web browser like Firefox or Chrome.
  • Servers are computers that store webpages, sites, or apps. When a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser.

Read More on MDN

What makes up a web page?

A website is made up of many different files. These files come in two main types:

  • Code files: Websites are built primarily from HTML, CSS, and JavaScript, though you'll meet other technologies a bit later.
  • Assets: This is a collective name for all the other stuff that makes up a website, such as images, music, video, or PDFs.
🔍 Further Exploration: How does the browser put the files together?

When browsers send requests to servers for HTML files, those HTML files often contain <link> elements referencing external CSS stylesheets and <script> elements referencing external JavaScript scripts.

  • The browser reads the HTML file first.
  • The browser looks for any <link>elements to external CSS stylesheets and any <script>elements that reference JavaScript files.
  • The browser sends requests back to the server for the CSS files it has found from <link> elements and the JavaScript files from <script> elements.
  • The browser builds the page from the HTML, applies the styles from the CSS, and executes the JavaScript. It shows the resulting page on the screen.
  • Then you see the page content, and can interact with it!

In this class, we won’t worry too much about how the other computer decides which files to send, or how to write other kinds of programs. If you continue to learn more about programming and web development, you’ll learn more about how that part of the system works.

If you’re curious about this topic, you can read more on MDN’s page on How the Web Works.

Practice: Draw the Web

👩🏾‍🎨 Draw what it looks like to load a webpage. Some ideas to include in your image: browser, server, files (HTML, CSS, JS)

  • Draw using whatever tool you like (such as paper, tldraw, or the built-in Padlet draw tool)
  • Take a screenshot, a phone picture, or export the image if you use a drawing tool
  • Upload the image to the Padlet (click the + button in the bottom-right, then add your image)
  • You can also choose to Draw from the Padlet "more" menu.

https://padlet.com/curriculumpad/230ru4pldu3v5md9

HTML Elements and Attributes

In this lesson, you’ll revisit HTML in more detail, and learn about more elements.

HTML Basics

HTML Example

Here’s an example. On the left is HTML. On the right is the same code, rendered as a webpage.

<p>
    This is a paragraph. It has an
    <a href="https://example.com">
        Example Link
    </a>
    inside the paragraph.
</p>
<img src="https://web-foundations.vercel.app/lessons/foundations/html-elements-and-attributes/valley-waterfall.png" alt="this is an example image" />

This tool is called CodePen, and we'll use it to demonstrate snippets of HTML, CSS, and JS. You can use it as a small playground for experimenting.

HTML Elements

HTML is made of text you can type on your keyboard. In addition to normal words, there are special words in angle brackets, like <p>, <a>, and <img> that add structure to the content.

The building blocks of HTML are called elements. A webpage is made up of elements.

  • Elements have different types
  • Elements can nest inside each other
  • Elements can have attributes

Types and Tags

There are lots of types of elements. In the snippet above, the elements are:

  • <a> stands for ‘anchor’, but means link
  • <p> for paragraph
  • <img> for images

There are many many elements in addition to these three. You’ll learn about 20 to 30 elements in the course. You can always look them up if you forget.

Tags

The syntax that looks like <some name> is called a tag. It says what kind of element it is.

Elements usually have two tags: an opening tag, and a closing tag. They show where the element starts and where it stops.

<p>Opening first, then closing</p>
  • The opening tag is <p>
  • The closing tag is </p>, with a forward slash / before the p.
📺 Here is a summary of HTML Tags

Nesting HTML Elements

HTML elements can go inside of each other. Everything that’s in between the opening tag and the closing tag is ‘inside’ an element. It can be text, like the paragraph above, or other HTML elements, or both. The element inside another element is called the child element while the one outside is the parent. Here's an example showing a <p> element inside an <a> element.

nested element

HTML Attributes

HTML elements often have more information.

This kind of information goes in an element’s attributes. Attributes provide more information about how an element should work.

For instance, an <img> tag can say where to find the actual image. An <a> tag can tell where to link to. Here’s some examples:

  • the src (source) of an <img> (image) element tells the browser where to go to find the actual image to put there:

    <img src="valley-waterfall.png" />
    
  • the href (hypertext reference) of an anchor tag (<a>) tells the browser where the link should go when you click it.

    <a href="https://example.com">The text that shows up</a>
    
  • the class attribute of any element helps identify it as part of a group. It’s really useful for styling and adding interactivity.

    <p class="nice">Hello world!</p>
    

HTML Element Anatomy

📺 Here's a video recap on HTML Attributes

Elements to know

There’s more than 200 HTML elements, you can see them all on MDN. You don’t need to memorize all of them. There are tons of them you’ll never ever use!

Here’s the ones that you'll use this week.

📺 Check out this video on Hyperlink

<a> stands for ‘anchor’, but means link. It’s the element that connects the whole web together.

  • The href attribute determines where the link will go when clicked
  • Whatever’s inside the tag is clickable as a link

See the Pen a tag demo by Rob Cobb (@rrcobb) on CodePen.

Further Exploration: Hyperlinks

Read more about the <a> tag and hyperlinks on MDN.

Topics to explore:

  • URLs, paths, absolute and relative paths
  • email (mailto) and phone (tel) links
  • urls, absolute and relative paths, and files
  • download links
  • linking directly to a part of a page

Image: <img>

Images make the web visually appealing. The <img> tag tells which image to add, where.

  • The src attribute says where to find the image
  • The alt attribute has a text description of the image, for accessibility

See the Pen Example of an img tag by Rob Cobb (@rrcobb) on CodePen.

📺 Check out this video on Images
Challenge: 🤔 How would you make an image that linked to another page?

Answer

You put the image inside the link, like this:

<a href="https://kibo.school">
  <img src="valley-waterfall.jpeg" />
</a>

When someone clicks on the image, it will navigate to the URL, just like a text link.

Further Exploration: Images

Read more about <img> and Images in HTML on MDN.

Topics to explore:

  • URLs and paths for images
  • types of image files
  • alt text and screen readers
  • setting image width and height
  • figures and captions
  • background images

Also check out this video about images and Pixels from Code.org

Text

Text Nodes

Inside a <p>, an <a>, or lots of other tags, you’ll see regular text. Text placed inside many elements shows up on the page. Sometimes, depending on the element, the text will show up differently.

Text Elements

<p>: Paragraph

<p> is for paragraph. It’s for the body text that makes up the bulk of text-heavy pages.

  • Paragraphs show the text inside the tag. They don’t make the text show a special way.
  • Each paragraph gets shown on a new line when the page is displayed.

See the Pen p tag demo by Rob Cobb (@rrcobb) on CodePen.

📺 Here's a video recap of the Paragraph tag

<h1> to <h6>: Heading

  • There are six heading elements.
  • The biggest one is h1, the smallest is h6
  • They are used for the title of the page, section and subsection titles

See the Pen heading demos by Rob Cobb (@rrcobb) on CodePen.

<ul>, <ol>, <li>: Lists

There are two kinds of lists. Unordered Lists <ul> have dots before each item. Ordered Lists <ol> have increasing numbers before each item. Both lists use <li> for list items.

See the Pen List Demos by Rob Cobb (@rrcobb) on CodePen.

<strong>, <em>: emphasized text

  • Both of these tags indicate that text is emphasized in some way
  • <strong> is a strong emphasis, for really important information
  • <em> is for information that’s different from the norm, but not as strongly emphasized

See the Pen strong and em demos by Rob Cobb (@rrcobb) on CodePen.

Practice: Find a new tag

🔍 The Mozilla Developer Network (MDN) is a top source of tutorials and reference materials for Web Developers.

Starting at the MDN overview page on HTML, find a description for an HTML element that’s new to you. Using the link below, share:

  • the name of the element
  • the link to the MDN page, and
  • what you find interesting about it

https://padlet.com/curriculumpad/xi54mrqkyua1qjww

Practice: Use the basic elements

👉🏿 Your turn! Use these tags to mark up the page.

  • Use this space to practice writing the basic elements.
  • Don't worry about the content of the page, it can just say "This is a heading" for the headings, and "this is a link" for the links.

To complete this, try to include:

  • a paragraph
  • a link
  • an image (there's an example image called example.jpeg in the sidebar)
  • two headings, of different levels
  • an unordered list
  • an ordered list
  • some emphasized and strongly emphasized text

Re-read the lesson or look up the elements using Google if you get stuck.

CSS Selectors and Properties

Let's dive deeper into CSS selectors and properties.

CSS

CSS controls the appearance of HTML elements. CSS is made of rules that look like this:

p {
    color: red;
}

This CSS sets the color of the text within paragraphs to red. Here’s the result:

paragraph rendered with red text

Try It: Change the Color

👉🏿 Your turn! Practice changing what shows up on the page by editing the CSS.

Set a timer for 10 minutes to experiment with HTML and CSS.

  • Try changing the text in the paragraph.
  • Try changing the CSS so that the color is blue.

If the embed below doesn’t load, use this link to open the page directly: https://codepen.io/rrcobb/pen/poKeopy

See the Pen Try it: Change the color by Rob Cobb (@rrcobb) on CodePen.

Linking CSS

📺 Check out this Code.org video on how to link your CSS

We’ll put our styles in a CSS file, usually called style.css. We need to tell the browser that this file is "linked" to the content in our HTML file.

In the HTML file, we’ll link to style.css using the <link> tag:

<link href="style.css" rel="stylesheet" type="text/css" />
  • The href attribute of the link says where to find the CSS file
  • The rel attribute of the link says what the relationship is to the page — for us, always stylesheet.
  • The type attribute of the link says that the kind of file it is — always text/css for us.

Add the <link> tag to this HTML page so that the styles are connected.

👉🏿 Use the link below to attempt the practice exercise

opes-tea-shop

CSS Syntax

Each rule has a selector and a list of declarations. The selector says which elements should get these styles.

css syntax

The selector is p, so all the <p> elements get the styles.

A declaration is a property and a value.

The property is color and the value is red

CSS selectors

When you write CSS, the steps often go:

  1. Pick what elements to style
  2. Edit their styles in the DevTools
  3. Write the style rules in your CSS file

Step 1 is “Pick what elements to style”.

Selectors determine which elements will get which styles.

See the Pen css selectors intro by Rob Cobb (@rrcobb) on CodePen.

The selectors in this example are p and a.

Question: Which elements get color: red;?

Answer: The paragraphs, because of the p selector.

Question: Which elements get color: green;?

Answer: The link, because of the a selector.

How selectors work

Selectors pick all the elements that match, and the style rule applies to all those elements.

There are lots of kinds of selectors. We’ll focus on the three most common selectors (Element Selectors, Class selectors, and id selectors) and how to combine selectors. Then, you can practice with more advanced selectors too!

Element Selectors

From the example above, p and a are Element Selectors. They select all the elements that are that type.

Question: How would you select all the images on a page and give them height: 100px?

Answer: The selector would be img, and the full CSS rule would be

img {
	height: 100px;
}

Class selectors

When an element has a class attribute, there’s special syntax to select them.

See the Pen class selectors demo by Rob Cobb (@rrcobb) on CodePen.

The selector .cool-paragraph selected the second paragraph, because it had a matching class attribute. The syntax is . plus the name of the class, in this case cool-paragraph.

You can have lots of elements with the same class. There can be lots of cool-paragraphs.

id selectors

An id selector selects elements that have a matching id. It’s similar to a class selector, just a slightly different syntax.

See the Pen id selector demo by Rob Cobb (@rrcobb) on CodePen.

#paragraph-6 picks the paragraph with the id paragraph-6. The syntax is a # plus the id (like paragraph-6). There’s only supposed to be one element with any particular id.

Combining selectors

Matching either selector ('or')

You can select more than one element with a combined selector.

The easiest way is to list multiple selectors, separated by commas.

p, a, .cool-text {
	color: hotpink;
}

All paragraphs, links, and elements with the cool-text class will be selected.

Matching both Selectors ('and')

If you put two selectors together, you select elements that match both selectors. You can select “the paragraphs that also have the class cool-paragraph” by combining the p and .cool-paragraph selectors like p.cool-paragraph.

There are other CSS combinators that let you pick elements that have relations like “all the links inside of list items” or “paragraphs right after second-level headings”.

Combinator is a fancy word for “thing that combines things”.

Here’s some examples:

  • .cool-paragraph strong selects all the <strong>elements inside elements with the cool-paragraph class.
  • h2 + p selects the paragraphs that immediately follow a level 2 header

You don’t need to memorize all the combinators.

If you want to see them and browse more examples, check out the MDN page on CSS Selectors.

📺 A video recap of CSS and Selectors

Practice: Select the Elements

👉🏿 Practice using selectors

In the CSS file, fill in the selectors for each of the rules so that the styles work.

See the Pen Try it: Select the Elements by Rob Cobb (@rrcobb) on CodePen.

Practice: CSS Diner

🍽️ For more practice with CSS selectors, try out CSS Diner.

There are 30 short exercises to practice selecting the plates, the food, or the table.

Try to get to at least Level 10!

A Taste of JavaScript

JavaScript lets you control the action on a page. It’s also a super powerful programming language you can use for all kinds of other applications.

Today, you’re just going to see how to link a JavaScript file to your HTML.

Script tag

We write our JavaScript in separate files, which in this course we’ll name script.js. To connect the JavaScript to the HTML page, we’ll use a <script> tag.

<script src="script.js"></script>

We use the src attribute to say where to find the JavaScript file.

Note: It’s called src for <script> tags. link and a tags have href, which is similar. If you mix them up, try switching to the other one.

We usually place the script tag at the end of the <body> tag, so that the rest of the page has loaded before the script is run.

👉🏿 Use the link below to attempt the practice exercise

Add the <script> tag to connect the JavaScript file to the HTML page.

taste-test

Deeper Connections: CSS Selectors in JS

Look at all the places it uses CSS Selectors:

document.querySelector('#gross')
document.querySelector('.reaction')
document.querySelector('#yum')

#gross, .reaction, and #yum are all CSS Selectors! When you learn to use JavaScript to create interactions, you’ll still use concepts from HTML and CSS.

The same CSS selectors that you use for styles will also let you pick HTML elements in your JS code.

In week 6, we’ll talk more about how the rest of the code works.

Browser Developer Tools

Web developers frequently need to see what's happening 'under the hood' on a website. The Browser Developer Tools (also called the “DevTools”, the “Inspector”, or the “Console”) give you that power.

The DevTools are awesome for seeing how a webpage is working, and testing out code. 👍🏿

The Devtools are safe It’s impossible to do any permanent damage to a website from the DevTools.

None of the changes you make in the DevTools are permanent. It’s a safe space to experiment. If something goes wrong, you can refresh 🔁 the page and get back to the original.

You can read more on MDN about:

Try it: Devtools Scavenger hunt

In this Scavenger Hunt, you’ll use the DevTools to view and edit properties of a webpage. You’ll get to explore for yourself what a webpage is made of, and practice using the tools that real web developers use to debug websites.

⚠️ If you get stuck on this assignment, watch the video below to see how to solve each clue.

Scavenger Hunt Solution Video

Week 1 Quiz

Due Date: 12th July, 2023; 11:59 EDT

The quiz for this week has been released on Gradescope - Quiz 1.

Week 1 Exercises

Due Date: 16th July, 2023; 11:59 EDT

In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. This will be the pattern throughout the course. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.

Mandatory Exercises

This week, the mandatory exercises are:

  1. Chicken Peanut Stew: In this exercise, you'll take a recipe that's written in text and turn it into an HTML page. You'll practice choosing the appropriate elements for different pieces of information and writing the HTML from scratch.

  2. Shirt City: Here, your task is to identify and fix errors in a given html file to obtain the desired result, as specified.

Accept the Assignment

Open the exercise on Github Classroom

Watch this Video on to download, test and submit your exercises

Quiz 2

Login to Gradescope and complete the weekly quiz before the live class session beings.

/assignments/quiz_1.pdf

Assignment 1

Checkout the project using the following link for GitHub Classroom. The assignments instructions are in the README file.

https://github.com/kiboschool/wdf-week-1-exercises

Advanced HTML

This week, you'll learn and practice more HTML tags.

There are more tags than you'll ever need to memorize. However, it's helpful to be familiar with lots of the common tags, so that you know which to reach for when building websites.

You'll also learn about Semantic HTML: using HTML tags that have the right meaning. Semantic HTML helps create well-structured, accessible, and search engine-friendly web pages while providing a better experience for users.

Learning Outcomes

After this week, you will be able to:

  • Use HTML Tables to structure data
  • Use Multimedia elements to embed content
  • Use common elements to create interactivity using HTML
  • Use Semantic HTML to add meaning to pages

HTML Tables

Did you know you can create table structures, using HTML tags? This lesson discusses how to do this.

A table in HTML consists of table cells inside rows and columns. A table in HTML can contain other tables. It can also contain other types of elements such as text, images, links, lists, etc.

Watch Video

Summary

  • use the <table> </table> tags to create your table structure.
  • Use the <tr> </tr> tags to add rows to your tables.
  • Use the <th> </th> tags to add table header.
  • Use the <td> </td> tags to add table data (content) or cell

Let's see an example

See the Pen HTML Tables by Ola (@OlaperiKB) on CodePen.

The table shown in example has three rows, which is why there are 4 pairs of <tr> ... </tr> tags in total. Each of the rows has three columns or data cells. The first row is the table header, therefore the <td> ..</td> tags were used. On the other hand, the last three rows are regular data cells, therefore the <td> ... </td> tags were used.

Activity

Create the table shown in the image below. Extra: You can also style your table by adding text colours, background colours and other styles possible.

Further Reading

Although we have covered the basics of a table, there are additional attributes and tags that can be used to create more complex tables.

Multimedia HTML Elements

Multimedia includes different content you can insert into your website, such as

  • video
  • music
  • voice notes
  • maps
  • slides
  • animations
  • ... and more!

In this lesson, you'll review the image tag, since it's similar to how other multimedia elements work. Then you’ll learn new multimedia HTML Elements.

Finally, you can review some of the elements you already know that create interactivity.

Review: Images

A lot of the new interactive elements work similarly to how images work.

<img src="valley-waterfall.png" />

The src attribute tells the browser where to find the image file, and the browser inserts the image at that spot in your site.

When styling images, you have to think about the width and height carefully so that you don’t break the aspect ratio. If an image is normally 100px by 100px, and you make it 50px by 200px in CSS, that will stretch out the image, and it will look bad.

When styling the new interactive elements, you’ll have to think about the same ideas: where’s the source url, and how do I style the element so that it looks right on the page.

<iframe>

Inline frames allow you to embed content from another site into your site. You can use them to embed tons of different kinds of content. In this curriculum, we use tons of embedded content — YouTube and Loom videos, forms, and interactive coding exercises.

A typical iframe might look something like this, which embeds a video from youtube.

See the Pen Iframe Demo by Rob Cobb (@rrcobb) on CodePen.

The src, width and height attributes are familiar from the <img> element.

  • src is the url where the browser should find the content
  • width and height control the width and height of the element

The other attributes are new:

  • title sets the title of the iframe
  • frameborder controls the border of the iframe. It’s often good to set it to 0
  • allow and allowfullscreen control the permissions that the iframe has. Since the content is coming from another website, you can decide what it is allowed to do.
Further Reading: iframe

Audio and Video

The <audio> tag is a built-in audio player. It lets you add audio content to your page, which the user can click to play.

<audio controls src="t-rex-roar.mp3"></audio>

Similarly, the <video> element is a built-in video player.

<video controls width="250" src="flower.webm"></video>

src and width work the same way they do for img and iframe.

The new attribute is controls. With controls added, the audio or video player will show the controls: play, pause, and volume.

It’s usually good to show the controls, since otherwise the user won’t be able to control the video or audio on the page. Usually, if they can’t control the audio or video, they’ll close the page instead of letting things autoplay.

src and source

<audio> and <video> tags allow specifying sources using <source> tags instead of the src attribute.

<video controls width="250">
    <source src="flower.webm" type="video/webm">
    <source src="flower.mp4" type="video/mp4">
</video>

Specifying multiple sources lets browser choose which kind of content to support. There’s fancy new formats like .webm that only some browsers can use, so if you write your code using <source>, users who have those browsers get the fancy new formats, and other users still get something that works for them.

Further Exploration: Multimedia and Embedding

For more, check out

Interactive HTML Elements

You have already seen elements and properties that help create interactivity.

They don't have to be multimedia elements to create interactivity!

<a>

Perhaps the most fundamental interaction on the web is clicking a link.

See the Pen Link Demo on CodePen.

<details> and <summary>

You may have also seen the <details> and <summary> elements which creates a toggle element that shows the details when you click the summary.

See the Pen Untitled by Rob Cobb (@rrcobb) on CodePen.

You've seen this combo in action!

We use the details and summary components in the lessons to hide away some of the content under a toggle.

There is always more underneath!

:hover and :cursor

You’ve also learned a couple of CSS tricks that create some interactive feeling:

  • Using the :hover selector to style elements when they are hovered (hover on MDN)
  • Using the cursor property to style the cursor (cursor on MDN)

See the Pen Untitled by Rob Cobb (@rrcobb) on CodePen.

These are basic kinds of interactivity, but don’t forget about them!

Semantic elements

Semantics refers to the meaning of a piece of code. It’s about "what purpose or role does that HTML element have", rather than "what does it look like?".

When approaching which markup to use, ask yourself, "What element(s) best describe/represent the data that I'm going to populate?”

MDN

HTML elements mean something. A <p> isn’t just styled like a paragraph, it tells other programs that the text inside really is a paragraph. We saw some semantic elements in the previous lesson, for example the <audio> and <video> tags that allow us to add audio and video content into a web page.

The <div> element is a commonly used tag, however, it is not a semantic HTML element. The <div> tag can be used to contain any type of information. On the other hand, the <header> tag can be used instead of a <div> to contain header information. In like manner, the <footer> element can be used to contain page's footer element at the end of the page. This way, we know exactly what type of information is contained in the element.

Other commonly used semantic HTML elements include the <nav> which is used to hold nagivational links and the <main>, used to encapsulate the main content of a page.

There are lots of kinds of “things” that go on webpages. For many of them, there’s a matching HTML element. Here’s some examples (there’s more than 100!)

List of Semantic Elements

  • <article>
  • <section>
  • <nav>
  • <footer>
  • <aside>
  • <details>
  • <summary>
  • <audio>
  • <video>
  • <figure>
  • <figcaption>
  • <aside>

Week 6 Quiz

Due Date: 14th August, 2023; 1:00PM EDT

The quiz for this week has been released on Gradescope - Quiz 6.

Week 6 Exercises

Due Date: 20th August, 2023; 11:59PM EDT

In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.

Mandatory Exercises

This week, the mandatory exercises are:

  1. Both Numbers are Even: In this exercise, you will implement a function to determine if two given numbers are even or not.

  2. Fizz Buzz: In this exercise, you will write a program to determine if a given number is divisible by 3 or 5.

  3. Count Characters in String: In this exercise, you will write a program to count the number of characters in a string.

  4. Can I Drive and Vote: In this exercise you will write a program to help determine if a person can either drive or vote, based on the person's age and country of residence.

  5. Can I Order Item: In this exercise, you will implement a function that checks if a specified dish is available in stock.

Accept the Assignment

Open the assignment on Github Classroom

Quiz 6

Login to Gradescope and complete the weekly quiz before the live class session beings.

/assignments/quiz_6.pdf

Assignment 5

Checkout the project using the following link for GitHub Classroom. The assignments instructions are in the README file.

https://github.com/kiboschool/wdf-week-6-exercises

More Functions, More Arrays

This week, we are going to continue exploring the fundamentals of the JavaScript language. Last week, we explored functions and arrays briefly. This week, we'll be going deeper and exploring more of their capabilities.

If you are yet to review the lessons from last week, or yet to fully grasp the concepts covered last week, it is advisable to go through the content again.

Finally, in programming, we always have errors. This week we'll also learn more about how to debug code and fix errors that we will inevitably have.

Learning Outcomes

After this week, you will be able to:

  • Use several Array methods
  • Use several Math properties and methods
  • Use several String methods
  • Understand how higher-order functions work
  • Debug your Javascript code more effectively

More on Arrays

Previously, we touched on arrays, in this lesson, we'll take a depper dive into arrays in JavaScript. You'll learn more about how to handle arrays and different array functions that exist.

Accessing Every Array Element

There is a for..of construct in JavaScript that helps to quickly navigate through every element in an array. The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object such as Array, and String. This construct is similar to the for loop syntax in Python.


for (variable of iterable)
    statement

Arrays are Objects

Do you remember the typeof operator used to determine the datatype of a variable, let's use that operator on an array and see what happens.

You see, the operator returned object because Arrays are actually a type of objects.

Array Methods

Arrays are objects, therefore they have properties and methods. We already saw one property of the array, length, which returns the size of an array, that is the number of elements in the array. Next, we'll review some array methods.

Watch this video on Array Methods

isArray() - Checking for an Array

From the previous example, we see that the typeof function cannot help us to confirm precisely whether a data type is actually an Array object. However, the Array object itself has a static method that can be used to determine if the value passed to it is actually an Array object.

	const anArray = [1,2,3,4,5];

   console.log(Array.isArray(anArray));
   //returns true

Read more about the isArray method here.

map()

If you need to modify every element in an array in a similar manner, you can use the map function. The map function itself takes in a function. For example, let's assume we have an array of numbers, and we want to multiply every element of the array by a certain number.

push()

The push() method is used add items into an array. It adds items to the end of an array. It takes in the value you want to add to the array.

Try it!

const shoppingList = ["Rice", "Bread", "Fish", "Beans"];

//Let's add a new item to our shopping list
shoppingList.push("Gaari");

console.log(shoppingList)

unshift()

The unshift() method is used to add an item to the start of the array. It takes in the value you want to add to the array.

Try it!

const shoppingList = ["Rice", "Bread", "Fish", "Beans"];

//Let's add a new item to our shopping list
shoppingList.unshift("Gaari");

console.log(shoppingList)

pop()

The pop() function is used to remove the last item from the array.

Try it!

const shoppingList = ["Rice", "Bread", "Fish", "Beans"];

//Let's remove "Beans" from our shopping list
shoppingList.pop();

console.log(shoppingList)

shift()

The shift() method is used to remove the first item from the array.

Try it!

const shoppingList = ["Rice", "Bread", "Fish", "Beans"];

//Let's remove "Rice" from our shopping list
shoppingList.shift();

console.log(shoppingList);

splice() and indexOf()

The splice() method is used to remove an item from a particular position, using its index. In last week's lesson, we saw the use of the indexOf() method, it simply returns the index of an item if it is present in the array. We want to remove the Bread item from our shoppingList, but Bread is neither at the beginning nor at the end of our array - the splice() method comes to the rescue.

Try it!

const shoppingList = ["Rice", "Bread", "Fish", "Beans"];

position = shoppingList.indexOf("Bread");
shoppingList.splice(position,1);
console.log(shoppingList);

Math Object

The JavaScript Math object comprises of several functions and constants that can be used to perform mathematical operations. It should be noted that the Math object doesn't have a constructor.

Watch this video on the Math object

Some Math Properties

The syntax for using properties of the Math object is Math.property. A few of the properties available are listed next. Try them out in the console to see how they operate.

Math Property Examples

  • Math.LN2 - This will return the natural logarithm of 2.
  • Math.LN10 - This will return the natural logarithm of 10.
  • Math.LOG2E - This will return base 2 logarithm of E.
  • Math.LOG10E - This will return base 10 logarithm of E.
  • Math.E - This will return Euler's number.
  • Math.PI - This will return Mathematical PI.
  • Math.SQRT2 - This will return the square root of 2.
  • Math.SQRT1_2 - This will return the square root of 1/2.

Math Functions

Math functions make it possible to carryout different computations. The syntax for using a Math function is Math.functionName(value). Example of Math functions includes Math.random(value), Math.round(value), Math.ceil(value), and Math.abs(value).

Watch this video on Math functions

Math.ceil()

This rounds a number up to the next largest integer.

Math.floor()

This rounds down a number to the next smallest integer.

Math.round()

This returns the number rounded to the nearest integer.

Math.trunc()

This returns the integer part of a number.

Math.max()

This returns the number with the highest value.

Math.min()

This returns the number with the lowest value.

Math.sqrt()

This returns the square root of a specified number.

Math.sin()

This returns the sine of an angle.

Math.cos()

This returns the cosine of an angle.

Math.tan()

This returns the tangent of an angle.

Math.abs()

This returns the absolute value of a number.

Math.pow()

This returns a number raised to a certain power.

Other examples of Math functions

  • Math.asin() - This returns the arcsine of a number in radians.
  • Math.acos() - This returns the arccosine of a number in radians.
  • Math.atan() - This returns the arctangent of a number in radians.
  • Math.sign() - This returns the sign of a number.
  • Math.log() - This returns the natural logarithm of a number.
  • Math.log2() - This returns the base 2 logarithm of a number.
  • Math.log10() - This returns the base 10 logarithm of a number.
  • Math.log1p() - This returns the natural logarithm of 1 plus number.
  • Math.exp() - This returns e (Euler's number) raised to given power.
  • Math.expm1() - This returns e raised to given power minus 1.
  • Math.sinh() - This returns the hyperbolic sine of a number.
  • Math.cosh() - This returns the hyperbolic cosine of a number.
  • Math.tanh() - This returns the hyperbolic tangent of a number.
  • Math.asinh() - This returns the hyperbolic arcsine of a number.
  • Math.acosh() - This returns the hyperbolic arc-cosine of a number.
  • Math.atanh() - This returns the hyperbolic arctangent of a number.
  • Math.atan2() - This returns arctangent of the quotient of arguments.
  • Math.fround() - This returns the 32-bit float representation of number.
  • Math.hypot() - This returns sqrt of the sum of squares of arguments.
  • Math.cbrt() - This returns the cube root of a specified number.
  • Math.clz32() - This returns num of leading zeros in binary of a number.
  • Math.random() - This returns pseudo-random float number between 0 and 1.

Activity

Try It! Pick 5 of these methods and try them out in your console.

String Functions

The JavaScript String functions are used to manipulate strings. They can be used to retrieve a subset of string from a specific string. They can also be used to modify a copy of string data. It should be noted when retrieving subset data, the functions use zero as a starting index.

Watch this video on String Functions

charAt()

It returns the char value present at the specified index.

charCodeAt()

It returns the Unicode value of a character present at the specified index.

concat()

It returns a combination of two or more strings.

indexOf()

It returns the position of a char value present in the given string. It will return -1 if the position couldn't be determined, i.e. if the character is not present in the string.

lastIndexOf()

It is similar to indexOf function, however it returns the position of a char value present in the given string by searching a character from the last position.

Other examples of String functions

  • search() - It searches a specified regular expression in a given string and returns its position if a match occurs.
  • match() - It searches a specified regular expression in a given string and returns that regular expression if a match occurs.
  • replace() - It replaces a given string with the specified replacement.
  • substr() - It is used to fetch the part of the given string on the basis of the specified starting position and length.
  • substring() - It is used to fetch the part of the given string on the basis of the specified index.
  • slice() - It is used to fetch a part of the given string.
  • toLowerCase() - It converts the given string into lowercase letters.
  • toLocaleLowerCase() - It converts the given string into lowercase letter on the basis of host's current locale.
  • toUpperCase() - It converts the given string into uppercase letters.
  • toLocaleUpperCase() - It converts the given string into uppercase letter on the basis of host's current locale.
  • toString() - It returns a string representing the particular object.
  • valueOf() - It returns the primitive value of a string object.
  • split() - It splits a string into an array of substrings based on a specified separator. It takes the separator as an argument and returns an array containing the substrings.
  • trim() - It trims off whitespace from the left and right side of the string.

Activity

Try It! Pick 5 of these methods and try them out in your console.

More on functions

Last week, we started our discussion on JavaScript functions. If you need a recap on functions, these two videos will be helpful.

In this lesson, we dive deeper into more details about functions.

Scope of variables in Functions

Variables defined within the scope of a function has a lifespan within that specific function alone and not available outside of the function in which it was defined. Step through the code snippet and watch the demonstration to see how the scopes of the functions and variables change.

1 function first(val){
2	  var name = val
3	  console.log(name)
4	  
5	  var addr = "residence"
6	  
7	  function second(val){
8	    var name = val
9	    console.log(name)
10	  }
11	  
12	  second(addr)
13 }

Arrow Functions

We talked a little bit about arrow functions last week, now let's see an example. Instead of the function keyword, we use an arrow => (the equal sign, followed by the greater than symbol). The arrow comes after the list of parameters, and is followed by the function body.

let power = (base, exponent) => {
    return base ** exponent;
}

Higher-order Functions

Higher-order functions are functions that operate on other functions, either by taking a function as an argument or by returning a function. In JavaScript, there are a number of built-in higher order functions, that take in functions as arguments.

We saw the map() function in the previous lesson. The map function takes in a function. You might also have a need to build your own higher-order function.

Let's look at an example of a function that is passed as a parameter to another function.

Debugging

This is the process of finding and resolving identified bugs within computer programs, software, or systems.

In JavaScript, the three frequently used methods in debugging an application includes:

  • Using the console within a browser enabled platform
  • Using a breakpoint
  • Using a debugger

Using the Console

The function console.log(<value>) can be used to display JavaScript values in the Console tab of our Devtools. This method is quite helpful, but it's not the most efficient approach. Notwithstanding, there are different ways to use the console for debugging.

Watch this Video on ways to use the console for debugging

Setting Breakpoints

A single or multiple breakpoints can be set in a debugger window. At each breakpoint, code execution will be paused, making it possible to examine available JavaScript values.

Watch this Video on how to set different breakpoints

The Debugger statement

The debugger keyword can be used to temporarily pause the execution of JavaScript code. This is similar to setting a breakpoint, however it has no effect on browsers that don't have support for it.

Watch this Video on how to use the Debugger

Week 7 Quiz

Due Date: 21st August, 2023; 1:00PM EDT

The quiz for this week has been released on Gradescope - Quiz 7.

Week 7 Exercises

Due Date: 27th August, 2023; 11:59PM EDT

In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.

Mandatory Exercises

This week, the mandatory exercises are:

  1. Prime Checker: In this exercise, you will write a program to determine if a given number is a prime number. You will also need to check if the given input is a number.

  2. Palindrome Checker: In this exercise, you will write a program to determine if a given input is a palindrome.

  3. Three-digit Armstrong: In this exercise, you will write a program to determine if a given number is an Armstrong number. You will also need to check if the given input is a three-digit number in the first place.

  4. Math Helper: In this exercise you will write a program to help calculate different math functions. This exercise combines the other three exercises in this week, namely, the Prime Checker, Palindrome Checker and the Three-digit Armstrong. Given a single interface, a user can specify which of the three math functions to be computed and the appropriate answer will be generated.

Accept the Assignment

Open the assignment on Github Classroom

Quiz 7

Login to Gradescope and complete the weekly quiz before the live class session beings.

/assignments/quiz_7.pdf

Assignment 6

Checkout the project using the following link for GitHub Classroom. The assignments instructions are in the README file.

https://github.com/kiboschool/wdf-week-7-exercises

DOM and Events

In the first half of the class, you learned how to build websites with HTML and CSS. The last few weeks have focused on the basics of the JavaScript language.

Finally, it's time to connect JavaScript to the HTML page.

JavaScript can change the HTML elements on the page, in response to events. In order to use JavaScript to change the HTML, you'll need to learn about the DOM: The Document Object Model. The DOM is how HTML elements are represented and accessed from JavaScript.

Once you can find, edit, and create elements from JavaScript, you'll learn how to react to events. Clicks, page loads, scroll, keyboard input, movement of the mouse – the browser knows about lots of events! You can listen for those events happening in JavaScript, and trigger an action to happen in response.

Learning Outcomes

After this week, you will be able to:

  • Find elements using common DOM methods
  • Manipulate DOM elements from JavaScript
  • Listen for and respond to user events

The Document Object Model (DOM)

When a web browser opens an HTML page, the browser builds up a model of the document structure of the HTML file, this model is used to draw up the HTML page on the screen. This model is called the Document Object Model, commonly referred to as DOM. This DOM is available to every JavaScript program, and with it, you can make live changes to your web page. It is an object that can be used to manipulate the structure, style and content of every web page. It is represented in JavaScript by the document object. The HTML DOM document object is the owner of all other objects in your web page.

Watch Video on HTML DOM

The Document Structure

You can picture an entire HTML document as a nested set of boxes. The boxes in this analogy represents the tags.

For example, consider the HTML document below:

<html>
    <head>
        <title>My DOM Tree</title>
    </head>
    <body>
        <h1>H1 in body</h1>
        <p> P in body <h1>H1 in P tag</h1></p>
        <p>Another p tag</p>
    </body>
</html>

Given the HTML page, the browser represents the page with a data structure similar to the set of boxes shown. Each box is represented by an object which can be used to find out which html tag it represents, which other boxes and text it contains, amongst other things.

nested element

You can also picture the DOM as a tree of nodes.

The document object

The document object gives access to all the objects on an HTML page. Its documentElement property refers to the object representing the <html> tag. The document object also has head and body properties which points to the head and body tags respectively.

The DOM Tree

The DOM is organized like a tree, in which elements are arranged hierarchically according to the structure of the document.

In Computer Science, a tree is similar to a real-life tree except that in this case, it is an upside down tree with the root above and branches beneath. The branches in a tree are referred to as nodes. Each node can have children nodes, parent nodes and sibling nodes. A tree also has leaves nodes. A leave node is a node which does not have children nodes.

The DOM object can be traversed as a tree and in this case, the document.documentElement property is the root. Nodes for elements, which represent HTML tags can have child nodes. An example of such a node is document.body. In the DOM tree, text and comment nodes are leaves nodes beacuse they cannot have children nodes (for instance, you cannot have a tag inside a comment node).

Now, let's visualize our previous HTML example with a Tree structure.

Document
└── html
    ├── head
    │   └── title
    │       └── "My DOM Tree"
    └── body
        ├── h1
        │   └── "H1 in body"
        ├── p
        │   ├── "P in body"
        │   └── h1
        │       └── "H1 in P tag"
        └── p
            └── "Another p tag"

As seen in the tree, the body node is a parent to an h1 node and two p nodes. These h1 and two p nodes nodes are siblings. The first p node has a text node and an h1 node as children. The last p node has a text node as a child and this is a leaf node, because it has no children nodes.

Which node is the parent node for the text node with the text "H1 in P tag"?

The h1 node, that is a child to the first p node.

Navigating the DOM Tree

In this lesson, we'll review how to navigate and access different elements in the DOM. As mentioned, in JavaScript, you can access the DOM through the document object. It represents the entry point to the DOM hierarchy and provides methods and properties to navigate and manipulate the document. There are lots of DOM methods and properties available, in this lesson, we will cover a few and then give reference to the full list.

Watch Video on DOM Traversal

We'll be using the html snippet from the previous lesson for our examples.

<html>
    <head>
        <title>My DOM Tree</title>
    </head>
    <body>
        <h1>H1 in body</h1>
        <p> P in body <h1>H1 in P tag</h1></p>
        <p>Another p tag</p>
    </body>
</html>

The parentNode Property

Each element in the DOM has properties to access its parent and child nodes. The parentNode property is used to get the parent of a particular node. The general syntax for this is: element.parentNode. element here is a reference to the element for which you want to get its parent. Let's see an example:

const html = document.documentElement;

//this displays the #document node as the parent
console.log(html.parentNode)

In this example, we get the object representing the <html> tag via document.documentElement, we then query its parent node which is the document object. Try this code snippet in your console.

Let's see another example.

const h1 = document.querySelector("h1");
console.log(h1.parentNode);

In this example, we get the first h1 element by using the querySelector() method , we then query its parent node, which is the body element.

We learnt previously how to use the querySelector() method. The querySelector() method allows you to select elements from the DOM using the CSS selector syntax. It returns the first element that matches the specified selector or null if no matching element is found. A closely related method querySelectorAll(), returns all the elements that match the given CSS selector.

The childNodes Property

Child nodes refer to the elements or nodes that are directly nested within another element. They are the immediate descendants of a particular parent element. Child nodes can include elements, text nodes, comments, and other types of nodes. To access the child nodes of an HTML element, you can use the childNodes property. Note that text nodes are created for whitespace between nodes, and are also seen as child nodes.

Run the given code snippet to see how the childNodes property operates. For the h1 node, it's only child is a text node, while the html node has multiple child nodes. The childNodes property returns a collection of child nodes.

const html = document.documentElement;
const h1 = document.querySelector("h1");
console.log(h1.childNodes);
console.log(html.childNodes);

The getElementById() method

To find a specific element, you can use it's unique id attribute in the html file with the document.getElementById method. The basic syntax to use it is shown.

const element = document.getElementById(id);

The getElementsByTagName()method

The getElementsByTagName method is another built-in method in JavaScript's DOM API that allows you to retrieve a collection of elements based on their tag name such as <div>, <p>, or <span>. It searches for elements with a specific tag name within a given parent element or the entire document. The method returns a live HTMLCollection or NodeList that contains all the elements matching the specified tag name. You can iterate over this collection to access or manipulate the selected elements.

Let's see an example.

//Gets all paragraph elements
let paragraphs = document.body.getElementsByTagName("p");

//Get the first paragraph element
firstParagraph = paragraphs[0]

The getElementsByClassName() method

The getElementsByClassName method like getElementsByTagName, searches through the contents of an element node and retrieves all elements that have the given string in their class attribute. The method allows you to retrieve a collection of elements that have a specific class name.

Here's the basic syntax of getElementsByClassName.

const elements = parentElement.getElementsByClassName(className);

className is the name of the class to search for. It is case-sensitive. elements is usually an HTMLCollection or NodeList containing the elements that match the specified class name.

Activity

  • If you skipped the video on this page, go back to watch it.
  • Try out all the examples in this lesson on your local computer.

Changing the Document

In the previous lesson, we looked at different ways we can navigate through the DOM object, document. Beyond navigating the document, we can also change or modify its structure.

Watch Video on DOM Manipulation

Adding and Removing Nodes

We can add or remove nodes or change parent-child relationships.

The remove() method

Nodes have a remove() method to remove them from their current parent node.

The appendChild() method

To add a child node to an element node, we can use appendChild, which puts the new node at the end of the list of children.

The insertBefore() method

This method takes in two arguments. It inserts the node given as the first argument before the node given as the second argument.

The replaceChild() method

The replaceChild() method is used to replace a child node with another one. It takes as arguments two nodes: a new node and the node to be replaced. The replaced node must be a child of the element the method is called on.

Some examples

Let's see how to use these methods by some examples. Our examples will use the following html page.

<html>
    <head>
        <title>My DOM Tree</title>
    </head>
    <body>
        <p>One</p>
        <p>Two</p>
        <p>Three</p>
        <script src="script2.js"></script>
    </body>
</html>
  1. To get all the paragraph elements in the page, we can use the getElementsByTagName method.

let paragraphs = document.body.getElementsByTagName("p");

  1. paragraphs[0].remove() will remove the first paragraph with the text One. Try this example on your VScode to see that the first paragraph gets removed.

  2. Running the code console.log(paragraphs[0]), will show you that the first paragraph is no longer a child to the body element.

  3. We can insert paragraph three before paragraph two by the following code: document.body.insertBefore(paragraphs[1], paragraphs[0]);

If you are inserting an already existing node, note that the node will be removed from its previous position to a new position. This is because a node can exist only in a single location in a document. Try these on your own to see how the code works.

Creating Nodes

You can also create new nodes in the HTML DOM via JavaScript code. You can create both text nodes and element nodes. Text nodes represent the textual content within an HTML document. They contain the actual text that appears between HTML tags or within an element. For example, consider the HTML snippet <p>Hello, <em>world</em>!</p>. Here, "Hello, " and "!" are text nodes. Element nodes on the other hand, represent the HTML elements themselves, such as <div> or <p>. They represent the structure and hierarchy of the HTML document. Element nodes can have attributes and child nodes.

Creating Text Nodes

Text nodes are created with the document.createTextNode() method. Given a string, createTextNode() gives us a text node that we can insert into the document to make it show up on the HTML page.

Let's add a text node to our HTML page.

newTextNode = document.createTextNode("Hello there")
document.body.appendChild(newTextNode)

First, we created a new text node using the createTextNode method. Next, we added it to the body node using the appendChild() method. Try this on VScode to see your new text on the browser.

Creating Element Nodes

To create an element node, use the document.createElement() method. This method takes a tag name and returns a new empty node of the given type. You can then append the new node to another element node to add it to the DOM hierarchy.

// Create a new element
var newDiv = document.createElement("div");

// Set attributes, properties, or styles of the new element
newDiv.textContent = "Hello, World!";
newDiv.className = "myClass";
newDiv.style.color = "red";
newDiv.setAttribute('id', 'myid');

// Append the new element to an existing element in the document
document.body.appendChild(newDiv);

In the code snippet above, we created a new <div> element. We also set the element's textContent, className and color properties. Finally, we append the new element to the body of the html. Run this code to see the <div> element added. Additionally, navigate to the Elements pane of your DevTool to see the new <div> element and its properties.

See the example on CodePen below. As you would observe, the HTML does not have any element containing 'Hello World', but we have created this new element using JavaScript.

Activity

  • If you skipped the video on this page, go back to watch it.
  • Try out all the examples in this lesson on your local computer.
  • Here's another short and helpful video on DOM.

Events

Events are things that happen on your web application, which the system tells you about so your code can react to them. Usually, the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken when the event occurs.

For example, if the user clicks a button on a webpage, you might want to react to that action by displaying a form to be filled in. Other examples of events include when the user chooses a key on a keyboard, when the user closes a browser window, or submits a form, when an error occurs or when a page finishes loading.

Watch this video on Event Listeners

Handling Events

JavaScript allows you to respond to these events by attaching event handlers to specific elements or the document itself. An event handler is a block of code or function that is executed in response to an event. There are different ways to handle events.

  1. Inline Event Handling: Event handlers can be directly attached to HTML elements using the on attribute (e.g., onclick, onmouseover). This is not recommended for larger applications due to code mixing concerns.

  2. Traditional Event Handling: Use the DOM Level 0 event properties (e.g., element.onclick = function() {}). This approach however, only supports one handler per event per element.

  3. Modern Event Handling: This approach uses the addEventListener method to attach event listeners. This approach supports multiple listeners for the same event on the same element, and it is the recommended approach.

Using the addEventListener() method

The addEventListener method allows you to add any number of handlers on an element. Objects that can fire events have an addEventListener() method. Some events, such as click, are available on nearly any element. Other events are more specific, for example, the play event is only available on some elements, such as <video>.

The general syntax is to use the method is:

 element.addEventListener(event, listenerFunction);

event is a string representing the event type (e.g., "click", "mouseover"). listenerFunction is the function to be executed when the event occurs.

Let us see an example. Assume you have a button in your HTML file, and you want to configure an event listener to respond when that button is clicked.

<button>Button 1</button>

First you need to get the button:

const btn = document.querySelector("button");

Next you need to write the event handler function:

function alertBtn(){
    alert("I love JS");
}

An event handler function is a callback function that defines the actions to be taken when the event occurs. It receives an event object as a parameter, which provides information about the event and its properties. To get the event object, you can modify the function as shown below.

function alertBtn(event){
    alert("I love JS");
    alert(event.target.tagName);
}

Finally, add the event listener to that button element.

btn.addEventListener("click", alertBtn);

Let's put all these together using CodePen:

Click the button to see what happens!

As a recap, the steps required are:

  1. Get the element required. The target element to which you want to add the event listener.
  2. Write your event handler function.
  3. Use the addEventListener() method to attach the event listener to the target element.

Removing an Event Listener

To remove an event listener, use the removeEventListener method. The same function used to add the listener must be passed as a parameter to remove it. Let us assume we want a particular button to only act once. A user is only expected to click the button once. Therefore, we need to remove the event listener so that no action is performed when the button is clicked more than once.

<button>Act-once button</button>
<script>
  let button = document.querySelector("button");
  function once() {
    console.log("Done.");
    button.removeEventListener("click", once);
  }
  button.addEventListener("click", once);
</script>

The function given to removeEventListener has to be the same function value that was given to addEventListener. So, to unregister a handler, you’ll want to give the function a name (once, in the example) to be able to pass the same function value to both methods, rather than using an anonymous function.

See this example on CodePen. Unlike the previous example, here if you click the button after the first click, nothing happens. This is because the event listener has been removed.

The event Object.

As seen from the previous examples, we can get the event object that was fired from the event handler function.

The information stored in an event object differs per type of event. The event’s type property always holds a string identifying the event (such as "click" or "mousedown"). In the alertBtn function, insert the code: alert(event.type);. This will display click indicating that a click event occurred. The target property of the event object refers to the element on which the event was originally triggered.

Watch Video on Events

Week 8 Quiz

Due Date: 28th August, 2023; 1:00PM EDT

The quiz for this week has been released on Gradescope - Quiz 8.

Week 8 Exercises

Due Date: 03rd September, 2023; 11:59PM EDT

In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.

Mandatory Exercises

This week, the mandatory exercises are:

  1. Click Counter: In this exercise, you are going to count the number of times the user has clicked a given button on a website

  2. Hide the Bunny: In this task, you will make the image of a bunny disappear when the user clicks a given button.

  3. Kibo Slide Show: You can build a slide show using HTML, CSS and JavaScript. Try this exercise to find out how.

Accept the Assignment

Open the assignment on Github Classroom

Quiz 2

Login to Gradescope and complete the weekly quiz before the live class session beings.

/assignments/quiz_2.pdf

Final project


Due Date: 10th September, 2023

Description

Your final project will be a website you design and create with a team.

You’ve learned a ton about HTML, CSS, and JavaScript in this course. The final project is your chance to build a website of your own design from scratch.

There are few requirements. You must use the knowledge you learned in the course, as outlined in the rubric below.

Rubric

PointsCriteriaDescription
20 ptsSite is complete- valid HTML, CSS, JS
- no errors
- nothing on the site appears incomplete
10 ptsSite uses appropriate HTML elements- Should use at least 10 different elements
- Elements should be used for their intended purposes
10 ptsSite is styled effectively- Color palette creates contrast
- Appropriate spacing between elements
- Text is styled for readability
20 ptsSite uses JavaScript for interactions- Event listeners trigger actions on the page
- Trigger at least 10 different actions. Examples:
- Change the displayed text of an element
- Change an element's colour
- Change an element's background colour
- Create a new element
- Delete an existing element
- Hide an element
- Display an element
10 ptsCode is styled well- indented properly
- organized effectively
- appropriately commented
20 ptsDeploymentSite is deployed on Github Pages
10 ptsVideo DemonstrationA video demonstration of your site in 5 - 7 minutes
10 pts(Bonus) Additional featuresFor example, social cards or HTML media elements; a responsive website
100Total110 possible points with the bonus, scored out of 100

Topic and Design Guidelines

Your team gets to decide the topic for your final project. The challenge is to choose a design that is exciting to you, but is not so big that it’s overwhelming or impossible to complete.

Here’s some guidelines that can help you pick an exciting project you’ll be able to complete.

  • Your final project should be more advanced than the exercises you've done. It should be a complete website that achieves a goal.
  • Don’t plan to learn a whole new technology for the final project. Plan to use mostly what you’ve already learned (with a little bit more Googling for the things you run into along the way).

What features should you avoid?

  • Collecting data
  • Forms
  • Payment

We haven’t covered how to collect and save data from users. Don’t plan to build a banking app, a social media website, or an e-commerce site.

Submission

  • Submit your work on your Github Repository for the team.
  • Submit your source code on Gradescope as a team.
  • Submit the link to the video demo as a team on Gradescope.
  • Submit your work on Woolf, individually.

Guidelines on the Video Submission

  • Length of video should be between 5 to 7 minutes.
  • The video should begin with a brief overview/description of your website.
  • Video should show all pages of the website (running on a browser).
  • Video should contain a code walkthrough, going through all your HTML, CSS and JavaScript files.
    • Explain your choice of HTML elements, CSS layouts etc.
  • Upload the video to Youtube using your Kibo account and submit the link.

How should you work together?

You’ll should figure out what works best for your team. The best teams communicate clearly up front, so that there isn’t confusion about what is going on. Try to agree on how you’ll communicate (Discord, Whatsapp, email, or something else), and when you’ll get together to work on the project.

It may be helpful to create a design doc. Using Google docs or a text file in Repl.it, write down your ideas. You might include links, images, drawings, and text that helps to explain what you are planning to build.

A design doc can also help you track what work you’ve done, and what work is left to do.

Accept the assignment

✨✨Have fun!✨✨

Advanced JavaScript

You've seen JavaScript basics, and how to use JavaScript to make changes on webpages in response to events. But, JavaScript is much bigger than what you can write on your own in a webpage!

JavaScript can run outside the browser. The most used outside-of-browser JavaScript runtime is called Node. It can be used much like Python -- from the terminal, as a scripting language, or on a server.

JavaScript also has libraries of code that you can use, called modules. You'll learn how to load code from modules into your own projects. You'll also see how you can use HTML and CSS libraries and frameworks.

Finally, you'll get a glimpse of how the practice exercises have worked all this course, with a look at testing.

Final Project

This week, you'll also begin work on your final project.

Learning Outcomes

After this week, you will be able to:

  • Run JavaScript programs in the terminal with Node
  • Install and use JavaScript modules
  • Use HTML and CSS libraries
  • Read and write basic JavaScript tests

Node.js

Running JavaScript without a Browser

Did you know that JavaScript can run outside of a browser? Well, yes. Although JavaScript began as a simple scripting language that only runs behind web pages on browsers, it has grown to become a versatile programming language that can be run outside of a browser environment.

In the world of web applications, JavaScript can also run on the server-side, to program the back-end of web applications. With the help of independent JavaScript runtime environments, it is possible to run JavaScript outside of a browser, on the server. Such runtime environments include Node.js, Deno, and Bun. Node.js is the most popular at the moment (early 2023).

Node.js is an open-source, cross-platform JavaScript runtime environment. It was originally written in 2009 by Ryan Dahl. It is very popular and quite easy to use.

Next, we'll have a sneak peek of how to run JavaScript on the command prompt using Node.js.

Watch Video on Node.js

Running JavaScript with Node.js

Note: You may have already installed node as part of your laptop setup. Read through the installation below to see the steps, then check if you have node installed by running node -v in a command prompt or terminal.

  1. Download and install Node.js. Visit the download page to download the relevant installer for your operating sysytem. It is usually preferred to download the long-term support (LTS) version, as they are more stable. To check if you already have it installed, type in node -v into your terminal/command prompt. If you have it installed, it should display the version you currently have installed. For example v18.16.1. Note that you might have a different version installed.

  2. Get your script, the JavaScript file you want to run. It should be a standalone file, without referencing anything related to the window or browser.

  3. Run it! To do this, open up the terminal, navigate to the directory your file is located and use the node command.

node filename.js

Activity

Now is the time to try it out. Download and install Node.js if you don't have it installed already, and try running a JavaScript file.

npm

NPM stands for Node Package Manager. It is the default package manager for the Node.js runtime environment. It consists of both a command line client, called npm CLI and an online database of packages, known as the npm Registry. The online database hosts thousands of free and proprietary packages that you can download and use.

The command line tool, npm is installed on your computer when you install Node.js. It can be used to download, install and manage packages.

node_modules, package.json, and the lock file

npm installs packages in a folder called node_modules. Because there are so many dependencies, the folder can get really big. It's also usually not something you want to store in git, or upload with the rest of your code. Instead, you can tell git to ignore the node_modules folder, and when you share your code, someone else will install the dependencies using npm.

npm keeps track of which libraries your code depends on in the dependencies key within the package.json file.

So that the version of each dependency is the same, npm stores a lock file with all the versions of each dependency. For npm, this is called package-lock.json.

pnpm

In this class, we use an alternative to npm called pnpm ("performant npm"). It has all the same features of npm, with a few exceptions:

  • instead of downloading packages directly to the node_modules folder, it downloads them to a central folder that it manages
  • it puts a link to the version of the package in the central folder into node_modules, so that there's still a copy of the package for your code to use
  • that means that it doesn't need to download any package that is already installed on your computer. npm would download a copy (and use lots of data) every time you install the same library in a different project.
  • it calls the lock file pnpm-lock.yaml.

Since we have lots of projects that use the same packages, pnpm can save you a lot of data. It can also work when you don't have a solid internet connection or are offline.

Note: Replacing npm with pnpm

Any command that you see online that uses npm, you can use pnpm instead. You might see other package managers mentioned online, like yarn. You can typically use pnpm instead when you see another package manager mentioned.

Download and Install a Package

To download and install a package, open your command prompt. Type in pnpm install followed by the name of the package to be installed. install is the pnpm command used to install packages.

When it installs a package, pnpm creates a folder called node_modules, where it stores the installed package. If this folder already exists, it simply adds the newly installed package to the folder.

Next, let's install a package called is-lower-case. To find out about this package and how to use it, search for it on the npm Registry.

To install it, type the following command on your command prompt: pnpm install to-lower-case

Using a Package

Once you have the package installed, you can then use it. To use the to-lower-case package in your JavaScript file, type in the following line of code:

var packageAlias = require('to-lower-case')

The line of code imports the to-lower-case package and assigns it to a variable called packageAlias. Feel free to replace the variable name to any name you want, and the package name to whatever package you want to use.

The require() function used is a built in function in Node.js that is used to import modules or packages into a JavaScript file. The argument given to the function is simply the package to be imported.

After importing the package, we then use the variable name, packageAlias in this case to access the functions exposed by the package.

In the to-lower-case package, there is a function called isLowerCase which we can use.

var packageAlias = require('is-lower-case')

console.log(packageAlias.isLowerCase("PascalCase"))

Note: import and es modules

require has been the keyword to load a node module since the introduction of node. Now, there is a new keyword import that loads modules slightly differently. Usually, you can use require without any trouble, but you may see import in other people's code, and the ecosystem is gradually moving to use import instead.

See this Cartoon deep dive into es modules

Activity

👉🏿 Try it: Create a file with the code snippet above and run it using node. false should be printed to the console because the string PascalCase passed to the function is not in lower case.

You can install, import and use any of the packages that are available in the npm Registry.

Modules and Packages

In programming, a module is a self-contained unit of code which encapsulates related variables, functions, or classes.

When you have a large project, it is usually great to split up the code into smaller modules which can be reused throughout the project. Each module will focus on a specific functionality or aspect of the larger program. This ensures code organization, encapsulation of related code within a single unit, reusability and modularity. Modularity ensures that you can isolate and test individual components of a program independently.

In JavaScript, a module can be exported, and then imported in another file for reuasbility. It is important to note that in JavaScript, there are two different module systems used. They are the ES modules (ECMAScript modules) and the CommonJS. ES modules are native to modern browsers and can be used directly in broswer environments that support ES6 or later. CommonJs modules on the other hand are not natively supported in browsers. This is because they were primarily designed for server-side environments such as Node.js.

In a future lesson on testing, you will see how to export and import modules using the CommonJS syntax. CommonJS uses module.exports to export a module and require() to import a module. You might have notices this syntax in your weekly practice exercises. It is good to note that Node.js supports both CommonJS and ES modules.

In this lesson, our focus will be on ES Modules. ES modules are the standardized module system for JavaScript.

ES Modules

ES Modules use import and export statements to import and export functionality between modules. This is closer to the syntax you will find in other programming languages.

Watch this video on ES6 Modules

Exporting a Module

To get access to a module in another script, the module has to be exported. This is done using the export statement. There are two ways to use the export statement.

  1. Use the export statement in front of any items you want exported. You can export functions, var, let and const variables. Using this approach, you can only export top-level items. You cannot use export inside a function.
export const name  = "Olaperi";

export function hello(name){
    console.log("Hello " + name);
}
  1. The second approach is to use a single export statetement to export all the items you want to export at once. This is done at the end of the module file. To do this, you specify your export statement, then a pair of curly brackets that contains a comma-separated list of features to export.
export{ name, hello};

Import Features into your Script

Once you have exported some features from a module, to use them in your script, you need to import them. The import statement is used to do this.

import {name, hello} from "./modules/module1.js"

The code snippet shows how we will import the exported name and hello features. In this example, we are assuming the module is in a file called module1.js and the file is inside a folder called modules. The script and the modules folder are both in the same folder.

Activity

👉🏿 Try it: Practice the use of ES Modules

  1. Create a new project, you can give it a name of your choice.
  2. Create a script.js file in your folder. Copy and paste the code below into the file.
import {name, hello} from "./modules/module1.js";

alert("Hello there!");
alert(name);
hello("Kibo student");
  1. Create an index.html file. Copy and paste the following code into the file.
<html>
    <head>
        <title>ES Modules</title>
    </head>
    <body>
        <p>Using ES Modules</p>
        <script type="module" src = script.js></script>
    </body>
</html>
  1. In the project folder, create another folder called modules.
  2. In the modules folder, create a file called module1.js.
  3. In module1.js, copy and paste the following code:
export const name  = "Olaperi";

export function hello(name){
    alert("Hello " + name);
}
  1. Now run your index.html file in your browser.

Optional Create another module in the modules folder and attempt the other approach of using the export statement.

Libraries and Frameworks

Libraries and frameworks are tools that provide pre-built features and functionalities that can be used to simplify and speed up the process of developing web applications. Libraries are collections of reusable code snippets, functions and components. Frameworks are sets of tools and components that offer a complete structure for building applications. Frameworks often follow specific design patterns and architectural principles, and they usually provide a foundation for organizing and managing your application. In web application development, libraries and frameworks help to handle common tasks, such as layout, responsiveness, form validation, and DOM manipulation. They make it possible for developers to focus more on application-specific logic and functionality.

There are different HTML, CSS and JavaScript libraries and frameworks that exist. Most times, these frameworks are not limited to either of HTML or CSS, they often include components from the different technologies, since they are all interconnected in web development.

Examples of libraries used in web application development include jQuery, D3.js, React, Vue.js. You can visit these websites to find out more about them and how to use them. In this lesson, we'll review an example using jQuery.

Examples of frameworks include Bootstrap, Foundation, Bulma and Tailwindcss

jQuery

jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document traversal, event handling, DOM manipulation, and animation. It was introduced in 2006 and has since gained widespread popularity and usage in web development.

To use jQuery in your project, you can either download the library and include it in your HTML file or reference it from a CDN (Content Delivery Network). Once included, you can begin using jQuery's functions and methods by writing JavaScript code that interacts with the jQuery object ($) and the DOM elements selected using jQuery selectors. It makes DOM manipulation and event handling simpler and faster.

Watch Video on jQuery

The code pen below shows an example of how to use jQuery.

The goal of the example is to hide the header element when you click the Toggle button. To do this, we are using a jQuery function called toggle(). To use any function from jQuery, you have to make the jQuery library available in your HTML document. In this example, we did that with the <script> tag, as in <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>, making the jQueryCDN as the source.

The $(document).ready() function is used to ensure that the jQuery code is executed once the document is fully loaded. Inside the click event handler, the $('#myHeading') selector is used to target the heading element with the id myHeading. The .toggle() method is then used to toggle the visibility of the selected element.

Feel free to explore the jQuery Library for many more ready to use functionalities for your application.

Bootstrap

Bootstrap is a popular CSS framework that provides a responsive grid system, a collection of pre-styled components, CSS and JavaScript utilities. Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many others. Basically, it makes the job of designing your application faster and simpler, minimizing the amount of CSS code that you have to write. With Bootstrap, you can build fast and responsive sites. A responsive website is one that automatically adjusts to look good on all devices, from small phones to large desktops.

To use Bootstrap, just like any other framework or library, you need to include the Bootstrap CSS and JavaScript files in your HTML document. You can either download Bootstrap and host the files locally or include them from a CDN (Content Delivery Network). All these details and options are right on the Bootstrap home page.

Watch Video on Bootstrap

Activity

👉🏿 Try it: Try out Bootstrap

  1. Get an index.html file that you've worked on previously. Ensure its not linked to any CSS file.
  2. Copy the code snippet below and place it within the <head> tag.
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
  1. Copy the code snippet below and place it within the <body> tag, just before </body>.
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
  1. Run the index.html file to see the difference.

Testing

Throughout this course, you've had sets of weekly exercises to work on, and you have had to run some tests on your exercises. Well, in this lesson, you'll have an idea of how those tests are written, and how to write your own tests.

But first, what is testing? Although we have used testing in this course to evaluate your work, testing goes beyond that. Testing of any code refers to the process of evauating the functionality, correctness and performance of your code, through the execution of tests. After writing any software code, it is important to check that your code behaves as expected.Testing helps you to catch bugs that exist in your code and verify that your code actually performs as expected.

There are different approaches to testing, one of these is called Unit Testing. Unit Testing refers to the practice of testing individual units of code in isolation. In JavaScript, units of code can be functions or modules. Unit tests verify the behavior of specific units to ensure they produce the expected output for a given set of inputs.

In JavaScript, there are different testing libraries and frameworks, that help to simplify the process of writing and running tests. Some of these include Jest, Mocha, Jasmine and QUnit.

In this course, the tests for your weekly exercises have been written using Jest. Next, let's have a look at the Jest framework.

Jest

Jest is a JavaScript Testing framework. Jest provides an extensive feature set and a user-friendly API, making it easy to write and run tests.

Watch Video on Jest Testing

Activity - JavaScript Testing with Jest

Let us go through a simple example using Jest.

  1. Open your terminal/command prompt.
  2. Type in pnpm init -y. This gives us a new project folder with a package.json file to get started.
  3. Next type in pnpm i --save-dev jest to install Jest.
  4. In the package.json file created, locate the code snippet below:
    "test": "echo \"Error: no test specified\" && exit 1"
  1. Change the value of "test" to become "jest", as shown below:
    "test": "jest"
  1. Create a file called sum.js. Copy and paste the code snippet into that file. This is the module we want to test. It contains a function that sums two numbers. We'll test the sum functionality if it performs as expected.
function sum(a,b){
    return a + b
}

//this line of code exports our sum function using the CommonJS module syntax.
module.exports = sum

  1. Create a file in the same folder as sum.js. Name this file sum.test.js. Copy and paste the code snippet into the file.

//this line of code imports the sum function from the sum.js file 
// so that we can test the function
const sum = require('./sum')

test('testing the sum function', () => {
    expect(sum(1,2)).toBe(3)
})

The test function is used to write tests in Jest. The first argument is a string describing the test. The second argument is a function that gets called to run this test. This is what helps to check our expected result. We use the expect jest test function to check the expected values. .toBe() checks that what the function returns equals to 3.

  1. To run your tests, type in pnpm test on your terminal. Jest will automatically detect and execute the test files matching the pattern *.test.js in your project directory. It will provide a summary of the test results, indicating whether each test passed or failed.

We do not expect you to become a test guru just yet, but this is just to give an idea of what testing is about.

Week 9 Quiz

Due Date: 04th September, 2023; 1:00PM EDT

The quiz for this week has been released on Gradescope - Quiz 9.

Mandatory Exercises

This week, the mandatory task is your final project.

Quiz 9

Login to Gradescope and complete the weekly quiz before the live class session beings.

/assignments/quiz_9.pdf