0% found this document useful (0 votes)
150 views

Programing Udacity

Uploaded by

alemu Regasa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

Programing Udacity

Uploaded by

alemu Regasa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Selectors: Combining

CSS selectors
 Overview: CSS building blocks
 Next

In CSS, selectors are used to target the HTML elements on our web pages
that we want to style. There are a wide variety of CSS selectors available,
allowing for fine-grained precision when selecting elements to style. In this
article and its sub-articles we'll run through the different types in great
detail, seeing how they work.

Prerequisites Basic software installed, basic knowledge of working with files, HTML basics
: (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective: To learn how CSS selectors work in detail.

What is a selector?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell
the browser which HTML elements should be selected to have the CSS property values inside
the rule applied to them. The element or elements which are selected by the selector are referred
to as the subject of the selector.

In other articles you may have met some different selectors, and learned that there are selectors
that target the document in different ways — for example by selecting an element such as h1, or
a class such as .special.

In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they
need to have support in browsers for them to work. The majority of selectors that you will come
across are defined in the Level 3 Selectors specification and Level 4 Selectors specification,
which are both mature specifications, therefore you will find excellent browser support for these
selectors.

Selector lists
If you have more than one thing which uses the same CSS then the individual selectors can be
combined into a selector list so that the rule is applied to all of the individual selectors. For
example, if I have the same CSS for an h1 and also a class of .special, I could write this as two
separate rules.

CSSCopy to Clipboard
h1 {
color: blue;
}

.special {
color: blue;
}

I could also combine these into a selector list, by adding a comma between them.

CSSCopy to Clipboard
h1, .special {
color: blue;
}

White space is valid before or after the comma. You may also find the selectors more readable if
each is on a new line.

CSSCopy to Clipboard
h1,
.special {
color: blue;
}

In the live example below try combining the two selectors which have identical declarations. The
visual display should be the same after combining them.

When you group selectors in this way, if any selector is syntactically invalid, the whole rule will
be ignored.

In the following example, the invalid class selector rule will be ignored, whereas the h1 would
still be styled.

CSSCopy to Clipboard
h1 {
color: blue;
}
..special {
color: blue;
}

When combined however, neither the h1 nor the class will be styled as the entire rule is deemed
invalid.

CSSCopy to Clipboard
h1, ..special {
color: blue;
}

Types of selectors
There are a few different groupings of selectors, and knowing which type of selector you might
need will help you to find the right tool for the job. In this article's subarticles we will look at the
different groups of selectors in more detail.

Type, class, and ID selectors

Type selectors target an HTML element such as an <h1>:

CSSCopy to Clipboard
h1 {
}

Class selectors target an element that has a specific value for its class attribute:

CSSCopy to Clipboard
.box {
}

ID selectors target an element that has a specific value for its id attribute:

CSSCopy to Clipboard
#unique {
}

Attribute selectors

This group of selectors gives you different ways to select elements based on the presence of a
certain attribute on an element:

CSSCopy to Clipboard
a[title] {
}

Or even make a selection based on the presence of an attribute with a particular value:
CSSCopy to Clipboard
a[href="https://example.com"]
{
}

Pseudo-classes and pseudo-elements

This group of selectors includes pseudo-classes, which style certain states of an element.
The :hover pseudo-class for example selects an element only when it is being hovered over by
the mouse pointer:

CSSCopy to Clipboard
a:hover {
}

It also includes pseudo-elements, which select a certain part of an element rather than the
element itself. For example, ::first-line always selects the first line of text inside an element
(a <p> in the below case), acting as if a <span> was wrapped around the first formatted line
and then selected.

CSSCopy to Clipboard
p::first-line {
}

Combinators

The final group of selectors combine other selectors in order to target elements within our
documents. The following, for example, selects paragraphs that are direct children
of <article> elements using the child combinator (>):

CSSCopy to Clipboard
article > p {
}

Summary
In this article we've introduced CSS selectors, which enable you to target particular HTML
elements. Next, we'll take a closer look at type, class, and ID selectors.

Which of these pieces of CSS will apply to span elements inside h2 elements?

The selector h2 span matches any span element inside an h2 element, which is just what
we want here!

What do you think happens if the selector on a rule doesn't match any elements in the
page? For instance, what if we have a rule such as ul { color: blue; } , but we don't
have any ul elements?
The rule will not do anything. It is really common to have the same CSS rules for all pages on a
web site; and if a particular page does not make use of a particular rule, that's OK!

Vocabulary Review
If you like, you can download this review as a PDF by clicking here(opens
in a new tab).
Here are some important CSS terms that you've learned so far:

 DOM (or Document Object Model) is a tree structure with a node for each
HTML element, piece of text, image, and any other object in the web page.
 Selectors are one part of the CSS ruleset. They indicate which HTML
element(s) the rule is for.

Example:

h3 {
text-decoration: underline;
}
h3 is the selector in this example.

 Declaration blocks are the other part of the CSS ruleset, they say how the
rule will modify the elements indicated by selectors.

In the above example, the declaration block includes the declaration of text-
decoration: underline; .

 CSS rulesets are composed of a selector followed by a declaration block.

Here are some examples of CSS rulesets:

.navigation-links {
font-weight: bold;
color: aqua;
}

#footer {
width: 100%;
background-color: purple;
}
li {
font-size: 10px;
margin-bottom: 10px;
}

 type is the simplest kind of selector. It indicates the name of one type of
HTML element (such as em or li).

In the above example, the type selector would be li.

 class in HTML is an attribute that groups elements together that you want to
have the same style.

In the above example, the class selector would be .navigation-links .

 id is an attribute that must be unique to a single element, used to identify it.

In the above example, the ID selector would be #footer.

Selectors Review
You've now learned about three kinds of CSS selectors: type, class, and ID!

Type selectors are used to apply a style to a particular type of HTML element,
like h1 or body. Type selectors are written using just the type name.

Class selectors are used to set the style for multiple HTML elements that
have a particular value for the class attribute. You can name a class anything
you want! Class selectors are written with a dot before the class: for elements
such as <p class="blue">, the class selector is .blue.

ID selectors are used when the style is being applied to one HTML element,
which has to have an id attribute. There can be only one element with a
particular id on a page. You can also choose any name you want for an id, just
like a class. ID selectors are written using a # sign: for an element such as <div
id="sidebar"> , the id selector is #sidebar .

Use this HTML document to answer the quiz below.

<html>
<head>
<style>
.special {
color: purple;
}
p {
font-style: italic;
}
#important-information {
font-weight: bold;
}
</style>
</head>
<body>

<h1 class = "special">This header is special</h1>


<p>A nice paragraph in italics.</p>
<h1>This header isn't so special.</h1>
<p>And this paragraph will be in italics too!</p>
<p id = "important-information">This paragraph needs to
be italicized and bolded!</p>

</body>
</html>
Quiz Question

Match the CSS selectors to the style elements they're used in.
p {
font-style: italic;
}
.special {
color: purple;
}
#important-information {
font-weight: bold;
}

CSS Selector

Style Element
ID selector
Type selector
Class selector
Practice: Selectors

What does this CSS ruleset do?

li {
color: green;
}
Applies a style to ALL lie elements on the page

CSS is used to define style, and HTML applies that style.

A rule is where we define the style, as in:


color:yellow;

li {
font-size: 1.5em;
color: blue;
}
The first example, with the li selector, uses correct syntax. html h1 { font-size:
1.5em color: blue; }

The second example, with the h1 selector, has a syntax error. It is missing a
semicolon ; before the property name color.

p {
text-align; center:
}
The third example. with the p selector, has a syntax error. The author has
swapped the semicolon and colon. The colon : should appear between text-
align and center, and the semicolon ; should appear at the end.

h2 {
text-align: center;
}
The fourth example, with the h2 selector, uses correct syntax.
We use a semicolon ; to show where each rule ends.

For example: p{color:green; text-align:center;}

Styling my to-do list


In the workspace below, you'll find my to-do list. But the list is very boring and
I'd like to add some styling to it.

To start with, I'd like to increase the text in the list by making it 1½ times
bigger than the current font size. That can be done using the following
declaration:

font-size: 1.5em;
You can apply this style rule to all of the list item li elements by using
a type selector. Give it a try!

<style>
li {
font-size:1.5em;
}
</style>
<h1>To-do:</h1>
<ul>
<li>Buy milk
<li>Buy eggs
<li>Buy flour
<li>Make waffles
<li>Do laundry
<li>Learn to code
<li>Build a robot
</ul>

Note: In our solution, we applied the style to all li elements, but we could apply it to the ul type
and (in this example) it would have the same result.

Practice: Class Selectors


My to-do list needs more work. I'd like to highlight the most important tasks in
yellow. And I'd also like to cross out the tasks that I've already done. It should
look something like this:
You can accomplish this by using two class selectors. I called
mine highlight and done, but you could choose other names if you prefer.

The style declarations (rules) that you'll need are background-color:


yellow; and text-decoration: line-through; .
<style>
li {
font-size: 1.5em;
}
.highlight {
background-color: yellow;
}
.done {
text-decoration: line-through;
}
</style>
<h1>To-do:</h1>
<ul>
<li class="done">Buy milk
<li>Buy eggs
<li class="done">Buy flour
<li class="highlight">Make waffles
<li>Do laundry
<li class="highlight">Learn to code
<li class="highlight">Build a robot
</ul>

Practice: More Class Selectors


So now the important items on my to-do list are highlighted, and the
completed items are crossed out. But what if I want to have an item that is
marked as both important and completed? Like this:

In other words, how can we apply two classes to one element?


This turns out to be pretty easy---we simply put in both of the class names,
separated by a space. Like this:
<li class="highlight done">Make waffles</li>

The power of separating style!


Let's do one more thing—I'd like the important list items to really stand out, so
let's also make them bold and red.

You can do that by simply adding a couple more declarations to the ruleset for
the highlight class:

.highlight {
background-color: yellow;
font-weight: bold;
color: red;
}
Give this a try in the workspace above!

Notice that if we were using inline styles, we would have to apply these
changes on every line of code with an li element. Here we only have seven—
but you can imagine how tedious this would get if we had a long list and
needed to update the styles on hundreds of list items!

Fortunately, because we have separated the style information, we can


make the changes in only one place (on the highlight ruleset) and they will
automatically be applied to all of the elements that have the highlight class.
This is one of the things that makes CSS so powerful!
\

What's So "Cascading" About CSS?


Cascading and Specificity

The term "cascading" in Cascading Style Sheets refers to the way that style
properties "cascade" down the DOM tree, starting at the top. A style applied to
the body element will affect the entire document. A style applied to a lower-
level element will affect that element and all its descendants.

A style applied at a lower level can override a style at a higher level. For
instance, if the body has color: red but a paragraph within the body has color:
blue, the blue will apply to that paragraph and to any elements inside it:

<style>
body { color: red; }
p { color: blue; }
</style>
<body>
<p> This will be blue, not red. <br>
<em> Same with this. </em> </p>
</body>

Practice: Cascading styles


Use the HTML below to answer the quizzes on this page!

<html>
<style>
body { font-style: italic; }
h1 { color: purple; }
body { color: green; }
p { color: orange; }
</style>
<body>
<h1> This is a very stylish document! </h1>
<h2> The styles are cascading </h2>
<p> So what color am I? </p>
</body>
</html>
Which elements of the HTML document are in green?

Look at the CSS ruleset again — is p set to be green?

body is set to green, but if a specific element is set to a different color that will override it!

Correct! h2 has no overriding color style, so it will be whatever color the body style is set to.
Units
1 inch =96 pixels

37.8pixels= I centimeter

72 pt. = 1 inch

Two of these units can be used in CSS for the height of an element.
One of them can't.

Which of these units can't be used for a height?

CSS allows you to specify heights (and other distances) using inches or centimeters, but a yard
(36 inches) is a much larger unit than we usually use on the web.

Use Developer Tools to inspect the red rectangle here. How big is it?

many cases, Developer Tools will default to showing you sizes in pixels.

What is the relationship between the CSS unit em and the HTML element <em>?

The CSS unit em is named for the size of the letter "M", and comes from print typography. The
HTML element <em> is short for "emphasis". They're spelled the same, and often
pronounced the same, but they have no other relation between them at all.

Boxes
Revisiting the div Element
In the video, you may have noticed that Kelly used the div element to create
the boxes. We looked briefly at the div element earlier, but it has been a while
—so, let's review the key ideas.

 It's used to divide up the page. The name div is short for division, because
that's what this element is for—you can use it to divide up the page into
different sections.
 It has an "invisible box" around it. Like the paragraph p element, the
division div element has an invisible box around it—and just like p, it can have
a border, a margin, a width, a height, and so on.
 It is a generic container. A p element is specifically meant to contain text. In
contrast, the div element is a generic container, meaning you can put
whatever other elements you want inside. You can use the div element to
organize the content and divide the page into sections.

The basic syntax is super simple:

<div>
</div>
And, we can texts inside the div, like this:

<div>
Example
</div>
And if we want to apply a style to a div, we can add a class attribute:

<div class="fancybox">
Example
</div>
And then, in our CSS, we can use a class selector with the same
name .fancybox to add whatever styling we want. Here's the example shown in
the video:

.fancybox{
border: 5px solid green;
margin: 1em;
padding: 0.5em;
width: 100px;
height: 50px;
float: right;
}
The div element is used all the time in HTML to structure web pages, so you'll
be seeing a lot more of it as you continue. On this page, we'll just be using
the div element to play around with boxes and adjust the margin, padding,
border, etc.
Quiz Question

With so much being invisible and happening behind the scenes, it can often
get confusing where margin, padding, border and content all fit.

To help get it sorted out in your head, see if you can put the parts of a box in
order, with 1 being the innermost part and 4 being the outermost—as shown in
this image:

Boundary

Placement

1 (innermost)
Content
2
Padding
3
Border
4 (outermost)
Margin
Exercise: Blue box
In the workspace below, practice making your own boxes! See if you can use
the div element to make a box with a thick blue border and some text inside,
like this:

<style>
.blue_box {
border: 10px solid blue;
padding: 0.5em;
width: 150px;
height: 100px;
}
</style>

<div class="blue_box">Hooray, a box!</div>

Practice: Boxes
Let's add a second box. But let's make it small, and red. Let's also put some
margin around both boxes, so that they aren't mashed right up against each
other.

Something like this:


<style>
.blue_box {
border: 10px solid blue;
padding: 0.5em;
margin: 0.5em;
width: 150px;
height: 100px;
}
.red_box {
border: 10px solid red;
padding: 0.5em;
margin: 0.5em;
width: 20px;
height: 20px;
}
</style>

<div class="blue_box">Hooray, a box!</div>


<div class="red_box"></div>

Practice: Floating Boxes


Now let's try out the float property. To start with, just try adding float: right; to
the blue_box class.

.blue_box {
border: 10px solid blue;
padding: 0.5em;
margin: 0.5em;
width: 150px;
height: 100px;
float: right;
}

What happened when you added float: right; to the blue_box class?

Note that the red box may shift up, but its horizontal position does not change.
Now try adding float: right; to the red_box class.

What happens?

Make sure you added float:right; to the red_box class with correct syntax.

Also, if the red box is moving all the way to the right, it might be because your
workspace is too small and it is wrapping things to try to fit them on the
screen. Try collapsing the menu and expanding the workspace, as shown
below:

Hm… that shouldn't happen. Double check that you added float:right; to the red_box class
—and that you didn't make a typo in your code.

Let's try one more thing—add a paragraph of text at the very end (after both
boxes). You can use this paragraph:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing


elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Mi sit amet mauris commodo. Vitae
elementum curabitur vitae nunc sed velit dignissim
sodales ut. Volutpat est velit egestas dui id ornare
arcu. Nulla facilisi nullam vehicula ipsum a arcu cursus
vitae congue. Porttitor lacus luctus accumsan tortor
posuere ac ut consequat. Et malesuada fames ac turpis.
Posuere lorem ipsum dolor sit amet consectetur
adipiscing. Sed risus ultricies tristique nulla. At
auctor urna nunc id. Pharetra convallis posuere morbi
leo. Quam quisque id diam vel quam elementum pulvinar
etiam. Eleifend donec pretium vulputate sapien nec
sagittis aliquam malesuada. Amet risus nullam eget felis
eget nunc lobortis.</p>
Note: If you're curious what this weird text is all about, it's something
called lorem ipsum. Essentially, it's nonsensical placeholder text that
designers commonly use when they're laying out a document. You can read
more about it (and generate your own lorem ipsum) here(opens in a new
tab).

ou can think of it as the boxes floating on the right side, and the paragraph
flowing around them.

It should look something like this:

Practice: Boxes Inside Boxes


Let's play with the boxes a little more.

If you recall, elements can have contents. Currently, only one of


our div elements has contents—the blue box contains the text Hooray, a box!

But instead of using text for the contents, we could use the other box. To do
this, we simply have to nest the div for the red box inside the div for the blue
box (replacing the current contents Hooray, a box!).

Like this:

<div class="blue_box">
<div class="red_box">
</div>
</div>
Notice how we've lined up the indentation to help make the nesting easier to
see.

It should look like this, with the red box inside and to the right:
The float: right; property causes the red box to be placed toward the right side
of whatever container it's inside. Since it is now inside the other div, it gets
floated to the right side of that div.

In case you're not seeing the results described here and need to troubleshoot,
here is the complete code:

<style>
.blue_box {
border: 10px solid blue;
padding: 0.5em;
margin: 0.5em;
width: 150px;
height: 100px;
float: right;
}
.red_box {
border: 10px solid red;
padding: 0.5em;
margin: 0.5em;
width: 20px;
height: 20px;
float: right;
}
</style>

<div class="blue_box">
<div class="red_box">
</div>
</div>

Percentages
Here's an image to refer to when answering the next question:
Question 1 of 2

Suppose we use the width property on an element, as in:


width: 50%;
What part of the element's box model is affected?

The width of the contents.


The width property only changes the width of the contents. The padding, border, and margin
are not included in the width (so they add extra width around the sides of the box!).
Interpreting percentages
Here is a piece of HTML with CSS. Use it to answer the question below!

<style>
.outer {
width: 300px;
border: 5px dotted orange;
}

.inner {
border: 5px solid blue;
width: 50%;
}
</style>
<div class="outer">
<p> This box has a box inside!
<div class="inner">
<p> How wide is the inner box,
<em>including</em> its border?
</div>
</div>
Use the HTML and CSS above to answer this question.

How wide will the inner box be, including its border?

The inner box's content will be 50% the width of the outer box's width, which would be 150px.
But the border adds 10px of width — 5px to the left, and 5px to the right.

150px is the width of the inner box's content, but that doesn't include the border.

Learning More CSS


you'll see much more about fonts later in this lesson.

A few of you who were extra thorough have sent us comments pointing out
that in addition to font-variant: small-caps(opens in a new tab), you can
also use font-variant-caps: small-caps(opens in a new tab). That works
too!
Separating Style
Stylesheet or style element — not both!
Note that you can put your CSS code inside of a <style></style> element, like
this ...

<style>
p{color:blue;}
</style>
... or inside of a linked stylesheet, like we just talked about.

But you would not want to do both at the same time! In other words, when you
place your CSS in a stylesheet, you don't need to use a style element—you
can just put the CSS directly into the stylesheet with nothing around it:

p{color:blue;}
This is what you should do for the exercise below—simply put the CSS
directly into your style.css file (and don't use the style element).

Linking stylesheets
To link to a stylesheet in your HTML file, add a link element to the head of the
HTML file. The syntax for the link element is just like this:

<link rel="stylesheet" href="style.css">


If you are linking to a stylesheet located on another web server, you will use a
full URL in the href attribute. If you're linking to one that's in the same directory
as your HTML file, you can just use the filename as a relative URL.

Creating a CSS file


You might think that creating a CSS file requires something special, but all
you have to do is make a new text file (just plain old text!) and rename it with
the extension .css. This is similar to how we create our HTML files—they are
simply text files that have a .html file extension in the name.

For example, in the workspace below, you can hover over the plus button and
select New File—and then simply name the file styles.css.
Practice: Three Ways to Style
At this point, we've learned three different ways to apply CSS styles to our
HTML elements. This can get a little confusing, so on this page we'll review all
three approaches. Try to notice what is different in each approach, and what
is the same.

As we saw earlier, we can't put CSS code directly in our HTML, because then
the browser will think it is HTML. Instead, we have to have a way of signaling
that the code should be interpreted.
emember, color: blue; is in CSS, which is a different language from HTML! We can't simply
place a piece of CSS code in the middle of our HTML—the browser will think the code is HTML
and not know how to interpret it (actually, in this case, it will just display color: blue; on the
screen, as if it were text).

This approach is called an inline style because the CSS style is added
directly into a line of HTML (by using the style attribute).

The disadvantage to this approach is that we would have to apply the inline
style over and over again—every time we want a paragraph of text colored in
blue, we would have to add this attribute to the p element. What if we had
1,000 p elements that should all be blue? It would get annoying really fast.

This approach allows us to partially separate our styling information. With


this approach, we would not have to add an inline style to every
single p element—instead, we can write a single line of code that applies the
style to all p elements.

It's not fully separated though. With this approach, the CSS is still in the same
file as the HTML.
This approach fully separates the CSS from the HTML. We can even link multiple HTML files
to the same CSS file if we want to!

OK, now it's your turn! In the workspace below, you'll see that someone tried
to apply some styles to some text, but it's not working. See if you can fix it!

Try using all three of the approaches we just discussed, so that you can see
them side-by-side:
 Make the paragraph of text centered using the style attribute to apply
an inline style.
 Make the text blue using the style element with a type selector.
 Make the text big using a linked CSS file (stylesheet). Note that the stylesheet
has already been created for you, but you'll need to add the style to it, and
add the correct link element to your HTML.

Note: Of course, you would normally not use all three of these approaches at
the same time like this—this is just for practice.
<link rel="stylesheet" href="style.css">

<style>
p {color: blue;}
</style>

<p style="text-align: center;">Style me 3 ways!</p>

Color
n school, you may have learned that the primary colors are red, yellow, and
blue. But in the video, Kelly said they are red, green, and blue. What's up with
that?

It has to do with how we are mixing the colors. When we mix a material
like paint the physics of how the color will look behaves very differently from
when we mix together wavelengths of light (which is what we need to do when
lighting up pixels in a computer screen). If you're super curious, you can check
out this article about primary colors from How Stuff Works(opens in a
new tab).

But for these lessons, all you really need to remember is that computers
use RGB colors—that is, red, green, and blue.
Which of these sentences accurately describes how to make shades of
gray using RGB colors?

Remember, you can use the browser's developer tools to experiment


with RGB values and observe how they influence the color output.

To make gray, use equal amounts of red, green, and blue. But if all three colors are equal to
zero, you'll get black; and if all three are the maximum value (255, FF, or 100%) you'll get white.
Try these color codes out in your browser. Which color matches which description?

Color code

Color description
#fed000
yellow
rgb(80, 5, 120)
dark purple
rgb(90%, 90%, 90%)
light gray

Additional Resources
If you were extremely observant you may have noticed that at the end of the
video (above), Kelly mentions HSL color. We didn't mean to get into that
here, but if you're curious, HSL stands for Hue, Saturation, and Lightness. If
you like, you can check out the w3schools.com page on HSL color(opens
in a new tab). If you scroll down on the page, they even have a live example
you can play with to see how HSL colors work.

Practice: Color
Kelly showed three different ways to represent color values in the code. For
example:

rgb(100%, 100%, 100%)


rgb(255, 255, 255)
#ffffff
Although they look different on the surface, they all work essentially the same
way.

In all cases, we need to give the amount (or you could say the intensity) of
each of the three primary colors: red, green, and blue (RGB).
Match each of these RGB values with the color it would produce.
Bright red
Bright blue
Dark green
Match each of these RGB values with the color it would produce.
These are the correct matches.

RGB value

What color is it?


rgb(255, 0, 0)
Bright red
rgb(0, 0, 255)
Bright blue
rgb(0, 102, 0)
Dark green

Notice that these are the same colors given in the last exercise. We can represent intensity on a
scale from 0-100% or on a scale from 0-255—they're just different ways of indicating the same
thing.

We've been using the words "amount" and "intensity". What we really mean
by this is the brightness of the light. Higher values indicate brighter (more
intense) light, and lower values indicate darker (less intense) light.

By mixing different levels of red, green, and blue, we can get different colors,
at different levels of brightness.

By the way, this way of thinking about light isn't limited to our code—if we
were to get real, physical lights and overlap them, we would get similar
results.
Red, green, and blue light overlap to create secondary colors and white light.
(Public domain image from Wikimedia Commons(opens in a new tab))
In the image above, notice that if we mix equal (and intense) levels of all three
colors, we get white light. And you can probably imagine that if we lowered the
intensity of all three colors by equal amounts, we would get various shades of
gray.

Match each of these RGB values with the color it would produce.
These are the correct matches.

RGB value

What color is it?


rgb(100%, 100%, 100%)
white
rgb(30%, 30%, 30%)
dark gray
rgb(0, 0, 0)
black
rgb(255, 255, 255)
white

Notice how we can specify maximum intensity of a color using either 100% or 255.

OK, but what about hex values, like #00cc66 or #99ccff?


These look strange, but they work the same way. Each pair of digits is a
number that gives the intensity of red, green, or blue. The reason these values
look strange is because they're in a different number system—instead of
the decimal(opens in a new tab) system that we are used to working with,
these numbers are given in the hexadecimal(opens in a new tab) system.

You don't need to have a deep familiarity with hexadecimal to be able to use
hex color values on your pages—but we'll briefly explain the basics so that
you can get a feeling for how they work.

Hexadecimal is not as complex as it might appear. Instead of having 10 digits


(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), hexadecimal has 16. Since we don't have 16
number symbols, hexadecimal counts up to 9 and then starts using letters.

Here is how we would show the numbers 0-15 in decimal and hexadecimal:

| Decimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---| | Hex | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |

Notice that it's the same until we get to 10, which is represented as A in
hexadecimal.

Like we mentioned, each pair of digits in a hex RGB value gives the intensity
of red, green, or blue. This ranges from 00, meaning zero intensity, to ff,
meaning maximum intensity. In fact, the number ff is the same as the decimal
number 255.

This may seem very alien, but take a try at the following exercise—just to get
a feeling for how hex values work.
Match each of these RGB values with the color it would produce.
These are the correct matches.

RGB value

What color is it?


#000000
Black
#ffffff
White
#ff0000
Bright red
#0000ff
Bright blue
f you need to find out what the hex value is for a particular color, you can
easily find out by using one of the many color picker tools that are available.

Check out this color picker from W3Schools(opens in a new tab).

You can enter a color in whatever format you like, and it will tell you what
other values can be used to represent that color.
If you haven't already, we encourage you to play around with the three
different kinds of RGB values we've shown here. Below is a workspace so you
can try them out.

We've added a linked stylesheet (the second tab in the workspace) with some
CSS type selectors that are already adding color to the background of
the body and h1 elements. But they're using simple color words
(black and white) rather than using RGB values (also, black and white are the
default values, so this isn't really doing anything).

Go ahead and replace the black and white with different RGB values. You may
want to use the W3Schools color picker(opens in a new tab) to find some
colors you like.

Practice: Searching for Properties


There are so many CSS properties out there, it's difficult to know (or
remember) them all! And even if you do remember the property you want, you
may not be able to recall the exact syntax. (Was it text-align: center; or text-align:
centered;?

Even experienced developers don't have every single property memorized.


Fortunately, it's usually easy to find what you need by looking it up in the
documentation or using your favorite search engine.

Most of the time, you can simply type in "CSS", followed by some words
related to the property. For example, if you want to know how to set the
background color, searching for "css background color" will turn up the results
you're looking for.

And as we've mentioned previously, the Mozilla Developer Network(opens


in a new tab) is a good resource to keep in mind (it also has a search option
you can check out).
Use the Mozilla documentation or your favorite search engine to find the CSS
property for setting an element's background color.

Fonts
Font vs Typeface
If you have worked in a word processor (like Microsoft Word, for example),
you may have seen things like Times New Roman, Courier, Arial,
or Helvetica. For example:

This Text is in Times New Roman

In word processors (and everyday speech) we would call this the "Times New
Roman font". But technically, "Times New Roman" is not a font—it is
a typeface.

Wait, what?

Most typefaces have multiple versions that look a little different from one
another. For example, we have:

Times New Roman italic

And also:

Times New Roman bold

These are all examples of the same typeface. but each one is a different
version or font.

A typeface is a group of related fonts.


A font is a specific version of a typeface.

Font Families
Another term we can use for a typeface (or group of related fonts) is a font
family. That's the term that CSS uses.
In other words, to change the typeface of our text, we can use the font-
family property. Like this:

font-family: Helvetica;
Or here's another example:

font-family: "Times New Roman";


Note: You might notice that one of these has quotes " " while the other does
not. The quotes are recommended for font families that have spaces in the
name. They help ensure that the name is read as one thing ( "Times New
Roman" ), rather than potentially three separate things ( Times, New, and Roman ).
The spaces don't usually cause a problem, so this is a recommended practice,
not a requirement (you can leave them off and it will typically still work).

Generic Fonts and Font Stacks


Generic Font Families and Font Stacks
Sometimes we don't care about the specific font family, but we do need the
text to use a general kind of font family. For this, we can use generic font
families.

Monospace as an Example

Compare these three examples:

This is an example
This is an example

This is an example
Each of these uses a different font family (or typeface). If you're curious, they
are Courier, Courier New, and Source Code Pro.
Even though they are different font families, they are all examples
of monospace font families. In a monospace font family, every character is
the same width—so, for instance, these two letters are the same width:

i
m
Monospace font families are really useful for writing code because they
ensure that everything lines up exactly as expected:

This is 27 characters long! And this is the


same length
We would not want to be writing our HTML or CSS and have different bits of
our code be different lengths depending on which letters are in that part of the
code!

So if we were putting some code on a web page, we might not care exactly
what font family it uses, but we would want to make sure it is some kind of
monospace.

Generic Font Families

That's where generic font families come in. There are five, each named for a
general kind of typeface:

 Serif
 Sans-serif
 Cursive
 Fantasy
 Monospace

In CSS, we can use a generic font family in place of a specific font family. For
example, this line specifies the specific font family Courier:

font-family: Courier;
In contrast, this one simply says to use whatever monospace font family is
available

font-family: monospace;
Font Stacks

Since we don't know what font will be available to each user, it's a good idea
to give multiple options. CSS allows us to do this by using a font stack, like
this:

font-family: Courier, "Courier New";


As you can see, we simply list the font families that are OK to use, with the
most-preferred choice first. If that choice isn't available, it will try the next one,
and so on.

A common (and very good) practice is to put the generic font family at the end
of the list, like this:

font-family: Courier, "Courier New", monospace;


This way, if none of the other font families are available, the browser will still
use the right general type.

More Font Properties


Font Size
To change the font size, we can use the font-size property, like this:

font-size: 24px;
In this example, px stands for pixels.

Bold
To make the text bold, we can use the font-weight property, as in:

font-weight: bold;

Italic
To make the text italic, we can use the font-style property:

font-style: italic;
Underline
To make the text underlined, we can use the text-decoration property:

text-decoration: underline

Font Shorthand
The Shorthand font Property
It can get a bit tedious typing all the different properties out individually.
Fortunately, there is a shorthand way to do this by using the font property.

For example, instead of typing out:

font-style: italic;
font-size: 24px;
font-family: Times;
We can simply use:

font: italic 24px Times;

…but it has to be in the right order

Like Karl mentioned at the end of the video, the downside to the shorthand is
that things need to be listed in a specific order, and it's kind of easy to forget
what that order is. Here are all the properties you can set using
the font shorthand and the order in which you would specify them:

1. font-style
2. font-variant
3. font-weight
4. font-size
5. font-family

Or to put that in context:

font: font-style font-variant font-weight font-size font-


family;
Here's an example that uses all five properties:

font: italic small-caps bold 24px "Times New Roman";


If you're able to memorize that, great! If not, you can do what Karl does and
just look it up when you need it. You can find it in this CSS-TRICKS
article(opens in a new tab), listed near the top of the CSS font property
documentation from W3Schools(opens in a new tab)—or simply Google
"font shorthand order".

Wait, what if I leave something out?


There are two properties that are required when you use
the font shorthand: font-size and font-family. Everything else is optional. If you
leave out one of the optional properties, it will just use the default.

For example, this specifies the font-style :

font: italic 24px Times;


But this one leaves it out:

font: 24px Times;


Since the font-style isn't specified, it defaults to normal (i.e., not italic).

Key Points About the font Shorthand

So, to summarize the three key points you need to remember:

 Font size and font family are required


 Things need to go in the right order
 If you leave an optional property out, it will use the default

font-weight: bold;
font-style: italic;
font-size: 14pt;
text-decoration: underline;

Below you'll find some pieces of code. Which of them are HTML and which are CSS?

Code
HTML or CSS?
<strong></strong>
HTML
font-weight: bold;
CSS
<em></em>
HTML
font-style: italic;
CSS
Something you may have wondered is why we have
both <strong></strong> and font-weight: bold;. If you want to bold some text, it
seems like you could use either of these—and they would have the same
results.

And the same seems to be true of <em></em> and font-style: italic;.

Why would we need CSS style properties like font-weight and font-style, when
we already have HTML elements like em and strong?

There are a couple of reasons for this.

The historical reason is that HTML was created before CSS, but the engineers
who designed CSS wanted it to provide more customization than HTML alone
did. The default way to show emphasis is by styling it as italic. But we don't
have to do it that way — we can use CSS to override the default styles. For
example, we could say that we want emphasized text to be red, or in a larger
font size.

But the differences go deeper than that. HTML code isn't only used by
browsers that display on the screen. It's also used by search engines, smart
speaker apps, and other programs. Those programs can't see "boldface" or
"italics", but they still need to know which text on a page is more important.

The em and strong elements specify the meaning of their contents. In contrast,
the CSS style properties are just specifying the visual appearance.

To repeat this in more general terms: the HTML indicates what the
contents mean, while the CSS indicates how the contents should look. Web
programmers refer to this as semantic markup — using markup to indicate
meaning, not just appearance.
For example, if we place some text inside an em element, this is our way of
indicating that this text should be emphasized in some way. But to a program
that's reading the page aloud to the user, it won't use italics; it will use tone of
voice. And even in a page that is displayed to the user, you might want it to be
emphasized using color or another property, instead of with italics.

In fact, why don't you give that a try. In the workspace below, you'll find some
text that uses a bunch of em elements. Apply a CSS ruleset to these that
makes them red and bold, but not italic!

Practice: Containers (1/2)


Earlier, we saw that we could put boxes inside other boxes. If those boxes
are div elements, then we simply nest the div elements inside one another:

<div>
<div>
</div>
</div>
One reason to nest boxes like this is so that you can use one of the boxes as
a container for the other boxes. To get an idea of why this would be useful,
let's take a look at an example.

In the workspace below, you'll find three boxes stacked vertically (notice that
they're currently not inside a container). You'll also see that there's a linked
stylesheet, and that we've styled the boxes using some different classes.

Suppose that we want to get all three of the boxes to stay in a vertical stack,
but move over to the right side. How can we do this?

Well, first let's try this: Add float:right; to the .box class, so that the boxes float
on the right side of the page. Then answer the questions after the workspace.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">
<title>Containers</title>

<link rel="stylesheet" href="containers_style.css">

</head>

<body>

<div class="box red">red</div>

<div class="box green">green</div>

<div class="box yellow">yellow</div>

</body>

</html>

Practice: Containers (2/2)


OK, so trying to float the boxes on the right individually didn't do what we
wanted—they ended up in a horizontal row, rather than staying in a vertical
stack.

To solve this, we can put the three boxes inside a fourth box. By wrapping
them in a container like this, we can then move the container around without
changing the arrangement of the boxes inside.

Flexbox
In the workspace below, you'll find all of the code that Kelly started with in the
video. Go ahead and try applying the two flexbox properties that Kelly
demonstrated (display and flex-wrap).

Note that these get added to the container element, not the inner boxes.

You should end up with a horizontal row of boxes that wraps when the
browser window is resized.

In case you're having trouble and need to troubleshoot, here's Kelly's full CSS
code:
.container{
width: 100%;
display: flex;
flex-wrap: wrap;
}

.box{
width: 100px;
height: 100px;
text-align: center;
font-size: 30px;
font-weight: bold;
font-family: sans-serif;
}

.red{
background-color: red;
}

.green{
background-color: green;
}

.yellow{
background-color: yellow;

Practice: Flexbox (1/2)


When using flexbox, it's important to understand how the size of the container
element affects the layout of the boxes that are inside of it.

You may have noticed that in Kelly's code, the width of the .container class is
set to 100%. That means the container will be as wide as whatever it's inside—
in this case, the container is inside the body element of the page, so it will take
up the full width of the page.

To see this more easily, we can add a border to the container class.

In the workspace below, add border: 5px solid black to the .container class.
Currently the width is set to 100%. Try changing it to 200 pixels ( 200px).
What happens?

⚠️Make sure you enter 200px and not just 200 . If you leave off
the px you'll get very different results!

As you can see, flex-wrap:wrap; causes the inner boxes to wrap to the second line when the
container becomes too narrow to fit them all horizontally.

n case you need it, here's the full CSS code with the changes we just made:

.container{
width: 200px;
display: flex;
flex-wrap: wrap;
border: 5px solid black;
}

.box{
width: 100px;
height: 100px;
text-align: center;
font-size: 30px;
font-weight: bold;
font-family: sans-serif;
}

.red{
background-color: red;
}

.green{
background-color: green;
}

.yellow{
background-color: yellow;
}
Practice: Flexbox (2/2)
et's get some more practice with flexbox. Your job here is to replicate this
checkerboard design:

We've given you a little starter code, but it's up to you to create all the boxes
and add the correct CSS.

This is very similar to the code we just went over on the last page, so if you
get stuck you can always look back at that (or check out our solution code
below).
Code for flexbox_practice.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flexbox practice!</title>
<link rel="stylesheet"
href="flexbox_practice_style.css">
</head>
<body>
<div class="container">
<div class="box red"></div>
<div class="box black"></div>
<div class="box black"></div>
<div class="box red"></div>
</div>
</body>
</html>
Code for flexbox_practice_style.css:

.container{
width: 200px;
border: 5px solid black;
display: flex;
flex-wrap: wrap;
}

.box{
width: 100px;
height: 100px;
}

.red{
background-color: red;
}

.black{
background-color: black;
}

CSS Syntax Review


We've gone over a ton of CSS syntax in this section, and we know it can be
hard to remember it all! This page provides a review that you can refer to as
needed. If you like, you can also download a PDF version of this page to refer to
later, such as when you're working on your final project (opens in a new tab).

Ruleset Syntax
The basic syntax of a CSS ruleset has two parts: a selector, and a group
of rules, each of which consists of a property name and the value of that
property.

selector {
property: value;
}
The selector is written first, and then the rules are written inside { curly
brackets }. Each rule's property and value are separated by a : colon, and the
rule always ends with a ; semicolon.

Selectors
The selector indicates which HTML elements the rule will apply to. You've
seen a few different sorts of selector: the element selector, the class selector,
the id selector, and the descendant selector.

A type selector applies to every HTML element of a particular type, such


as p or em. This selector will apply to every p element:

p {
color: blue;
}
A class selector applies to all elements that share a class attribute. The class
selector is written starting with a . (dot):

.narrow {
width: 20%;
}
In order for the class selector to apply, there have to be HTML elements on
the page that use that class attribute:

<div class="narrow">
This will get the 20% width.
</div>
An id selector applies to an element with a particular id attribute. The id
selector is written starting with a # sign:

#sidebar {
background-color: lightgray;
width: 20%;
float: left;
}
Within an HTML page, there should be only one element with that id attribute
value.

<div id="sidebar">
This will get the background, width, and float values
from the sidebar CSS rule.
</div>
A descendant selector is a compound of two simpler selectors. It applies
only to an inner element that is a descendant (on the DOM tree) of a particular
outer element.

li a {
color: pink;
}
The above selector will apply to a elements (hyperlinks), but only those inside
an li element (list item):

<ul>
<li> <a href="https://www.udacity.com/"> Pink Udacity
</a>
</ul>
<p> <a href="https://www.google.com/"> Non-pink Google
</a>

Rules
A ruleset can be composed of several rules, each of which applies a
particular value to a property of the selected elements. Properties are things
such as the color, position, size, and shape of the element.

h1 { color: red; font-size: larger; }


This rule applies the value red to the property color, and the value larger to the
property font-size.

Some properties allow values that are more than one word long, such as
the font property:

body { font: 12pt bold Consolas, Monaco, monospace; }


Font stacks

The font-family and font properties allow you to specify a font stack, a list of font
options separated by , commas. The browser will use the first font in the stack
that is available on the user's system. Usually the last font in the stack should
be a generic font name, such as serif, sans-serif, or monospace.

Colors

There are several ways to specify a color in CSS. Three common ones are
hex codes, rgb triples, and color names.

.orange {
color: #ff9900;
}
.pink {
color: rgb(100%, 80%, 80%);
}
.chartreuse {
color: chartreuse;
}

Flexbox
To change the browser's layout from the default document-based layout to the
flexible box layout, set display: flex on a container element (one that has other
elements inside it).

.outer {
display: flex;
border: 2px dotted orange;
}
.inner {
width: 100px;
border: 1px solid black;
padding: 10px;
}
Flexbox can be heavily customized! The above will cause .inner HTML
elements to be packed in a row within the .outer element:
<div class="outer">
<p class="inner"> I am a box. </p>
<p class="inner"> I am another box. </p>
<p class="inner"> Hey, I am a box, too! Boxes
<strong>rock</strong>. </p>
<p class="inner"> Let's be boxes together. Yay,
flexbox. </p>
</div>
I am a box.
I am another box.
Hey, I am a box, too! Boxes rock.
Let's be boxes together. Yay, flexbox.

Challenge: Replicating a Design


In the workspace below, try replicating the design of the tic-tac-toe board
shown in the video. There's also a copy of the image below the workspace.

To do this, you'll only need to add CSS rules to the file tictactoe.css . (You don't
need to edit the HTML file at all!)

Here are a few hints:

 The ul and the li elements have boxes just like the div elements we've been
working with. And you can think about the ul as a container for the li elements.
 Like Karl said in the video, you will probably run into a couple of places where
you need to look up CSS properties you haven't encountered before. For
example, you'll need some way of hiding the bullets in the bulleted list. (Karl
had to look that up too when he solved the challenge.) Google is your friend
here!
ul{
width: 300px;
height: 300px;
display: flex;
flex-wrap: wrap;
}

li {
width: 90px;
height: 90px;
font-size: 80px;
font-family: sans-serif;
background-color: lightblue;
margin: 5px;
list-style: none;
text-align: center;
}

======================

ul{
width: 300px;
height: 300px;
}

li {
width: 90px;
height: 90px;
margin: 5px;
float: left;
list-style: none;
font-size: 80px;
font-family: sans-serif;
text-align: center;
background-color: lightblue;

Intro to JavaScript
JavaScript was Created for the Web
JavaScript was created in 1995 to make it easier to add interactive and
dynamic elements to websites.

Today, JavaScript is used for all sorts of applications - from programming


robots to writing game scripts. Even some code editors were built with
JavaScript.

What You Will Learn


In this course, you'll learn the foundations of the JavaScript programming
language, from the history of JavaScript to how to:

 Run JavaScript code in the console of your web browser


 Create variables and use basic JavaScript data types to represent real-world
data
 Use conditionals to add logic to your JavaScript programs.
 Create loops to reduce code duplication and add automation
 Write functions to streamline and organize your code.
 Use arrays to store and manipulate lists of data.
 Use objects for even more complex data organization

If you're familiar with using HTML and CSS to create web pages, JavaScript is
the final piece you'll need to make your websites come to life!

Prerequisites
There are no prerequisites for this course.
History of JavaScript
Where Did JavaScript Come From?
The first version of JavaScript was created in just ten days 1995 by Brendan
Eich(opens in a new tab). Eich was working on Netscape Navigator, one of
the Internet's first web browsers. Eich's goal was to add the capability for
dynamic web pages, which, at that time, were simple pages of HTML and
CSS.

Why Is It Called Javascript?

JavaScript was originally called LiveScript, but it was changed back to


JavaScript as a marketing decision to piggyback off Java's popularity. Despite
the name, JavaScript is not related to Java in any way.

The Evolution of JavaScript

As the language evolved, competing versions of the language emerged. To


standardize the language, JavaScript was brought to Ecma
International(opens in a new tab), an industry association "dedicated to the
standardization of information and communication systems." That's why you
might hear JavaScript referred to as ECMAScript.

The standards body has transitioned to a year-based number to promote a


more consistent release cycle. So we have ES2016, ES2017, and so on. You
can see current specifications on the ECMA website. ECMA-262(opens in a
new tab), and you can even look over drafts of proposed
updates ECMAScript® 2022 Language Specification(opens in a new tab)

JavaScript Today

JavaScript has grown to be one of the most popular programming languages


globally and is considered one of the foundational pillars of front-end web
development.

You can read more about the current standards for JavaScript in MDN Web
Docs: JavaScript(opens in a new tab)

Want to Learn More?


Read a little history of JavaScript in Wikipedia(opens in a new tab).
TIP: HTML and CSS are markup languages*. Markup languages are used to
describe and define elements within a document. JavaScript is
a* programming language*. Programming languages are used to
communicate instructions to a machine. Programming languages can be used
to control the behavior of a machine and to express algorithms.*

The JavaScript Console

Using the JavaScript Console in Google Chrome


Note You can find instructions on how to access developer tools in other
browsers on the next page.

1. Open Developer Tools: Right-click on the page and select Inspect.


2. Open the Console: Click on the Console tab or use a shortcut
(Cmd+Option+J on macOS or Ctrl+Shift+J on Windows)
3. Write your code!: Here are some examples. Either type this into the browser
or copy it and paste the code into the console. Don't forget to hit return to run
the code.

"Julia"
alert("Hello, Julia! How are you?!");
Writing code in the console is a great way to test out simple bits of code, but
as your code gets larger the browser user interface can be awkward. We
recommend using a text editor like VSCode(opens in a new
tab), Atom(opens in a new tab), or Sublime Text(opens in a new tab) to
write your code and pasting your code in the console when you're ready to run
it.

We'll also provide workspaces for the quizzes and activities in this course.

Want to Learn More?

Learn about Chrome Dev Tools Keyboard Shortcuts(opens in a new


tab) to help you move around in the console more quickly.
Developer Tools on Different Browsers

Developer tools on different browsers


Did you know that every modern web browser includes its own set of
developer tools?

If you didn't, that's okay. Developer tools aren't always the easiest thing to find
in your browser. So, we've decided to help you out by creating this guide to
developer tools!

Google Chrome

The Chrome DevTools are a set of web authoring and debugging tools built
into Google Chrome. Use the DevTools to iterate, debug and profile your
site. Learn more about Chrome DevTools here(opens in a new tab).

To open Chrome DevTools, either right-click on any page element and


select Inspect or open the Chrome settings menu in the top-right corner of your
browser window and select More Tools > Developer Tools. Alternatively, you can
use the shortcuts:

 Command + Option + i (Mac)


 Ctrl + Shift + i (Windows/Linux).

Mozilla Firefox

Firefox Developer Tools allow you to examine, edit, and debug HTML, CSS,
and JavaScript on the desktop and mobile. Also, you can download a version
of Firefox called Firefox Developer Edition(opens in a new tab), which is
tailored for developers, featuring the latest Firefox features and experimental
developer tools. Learn more about Mozilla Firefox DevTools here(opens in
a new tab).

To open Firefox Developer Tools, either right-click on any page element and
select Inspect Element or open the Firefox settings menu in the top-right corner
of your browser window and select Developer. Alternatively, you can use the
shortcuts:

 Command + Option + i (Mac)


 Ctrl + Shift + i (Windows/Linux).

Microsoft Edge

Microsoft Edge introduced great new improvements to the F12 developer


tools seen in Internet Explorer. The new tools are built in TypeScript and are
always running, so no reloads are required. In addition, F12 developer tools
documentation is now fully available on GitHub(opens in a new tab).

To open developer tools in Microsoft Edge, simply press F12.

Learn more about Microsoft Edge DevTools here(opens in a new tab).

Safari

For any Mac users, Safari includes Web Inspector, a powerful tool that makes
it easy to modify, debug, and optimize a website for peak performance and
compatibility on both platforms. Learn more about Safari Web Inspector
here(opens in a new tab).

To access Safari's Web Development Tools, enable the Develop menu in


Safari’s Advanced preferences. Once enabled, you can right-click on any
page element and select Inspect Element to open Web Development Tools or
use the shortcut Command + Option + i.

Opera

Opera is a fast, lean, and powerful web browser. You can open Developer
tools in Opera using the following keyboard shortcuts:

 Command + Option + i (Mac)


 Ctrl + Shift + i (Windows/Linux).

Alternatively, you can target a specific element by right-clicking on the page


and selecting Inspect Element.

console.log
The Console Is Your Coding Sandbox
The console is a great place to mess around with your code without any long-
term consequences. The console will tell you if there are any warnings or
errors on the page, display any output, or print it with console.log.

Using console.log statements

console.logis used to display content to the JavaScript console. Run the


following code in the console:

console.log("hiya friend!");
Prints: "hiya friend!"
This can be very helpful in figuring out what is going on when you are
debugging your code.

NOTE: You may see some errors or warnings in the console from the site
you're visiting -- and that's okay! Warnings are very common and will not
affect the code you write in this course.

Troubleshooting

For Chrome users, if you don't see the output, click “Default levels” in the
console and make sure that "Info" is checked. Congratulations! You
performed the log action on the debugging console.

The message you’ve logged is "hiya friend!". hiya friend! is a string (a


sequence of characters).

Give It a Try!
Let’s use console.log to do something a little more interesting. Here’s a block of
JavaScript code that loops through the numbers 0 through 9 and prints them
out to the console:

for (var i = 0; i < 10; i++) {


console.log(i);
}
Prints:
0
1
2
3
4
5
6
7
8
9
This is called a loop.

Based on this loop's settings, any code written inside the curly
brackets {...} will be repeated ten times. In this case, console.log prints out the
value of i each time the loop runs. Don't worry if you're not sure about what
the syntax means at this point. Later in this course, you will learn more about
how and when to use loops.

console.log Demo

Other console methods

Browser console has other methods that can be very useful when poking
around. For example, try typing console.table(["orange", "strawberry", "banana"]) in
the console. This method will create a table and display the data in it.
You are welcome to explore the console.dir method on your own. Don't be
afraid to tinker!

For more information you can also refer to MDN


documentation: console(opens in a new tab).

JavaScript Demo
So you saw how to use console.log to print a message to the JavaScript
console. Now, let’s see how you can use the console as a sandbox to test a
new line of JavaScript in the browser.

Open the Daring Fireball website(opens in a new tab) in a new tab and in
that tab also open up developer tools. Then paste the following code:

document.getElementsByTagName("h1")[0].style.color =
"#ff0000";
NOTE: If you can't access https://daringfireball.net/(opens in a new tab),
try a different website like https://www.udacity.com/(opens in a new tab).
This demo will work on many different websites.

Project Preview
Build an eCommerce Shopping Cart
By the end of this course, you will understand enough JavaScript to build a
fully functioning eCommerce shopping cart for Kirana's Fruit Stand.

We'll provide the front end, which looks like this:


Completed Storefront
and you will write the code that makes it work.

You will create:

1. A list of products that users can buy


2. Functions to enable typical shopping cart functions including:
 Adding an item to a cart
 Increasing or decreasing the quantity of an item
 Removing an item
 Adding up the cost of all items in the cart
 Paying for the items

The code to connect your products and functions will also be supplied, so you
only need to focus on the JavaScript code.

Why This Project?


Our goal is to challenge you to think like a programmer and use the skills you
will learn in this course. This project barely touches the surface of what is
possible, but it does use many of the foundational skills that will make up the
majority of most of your future coding projects.

// Sample products const products = [ { id: 1, name: "Apples", price:


1.00 }, { id: 2, name: "Bananas", price: 0.50 }, { id: 3, name: "Cherries",
price: 2.00 } ]; // Cart object to hold items let cart = []; // Function to
display products function displayProducts() { const productContainer =
document.getElementById('products'); products.forEach(product => { const
productDiv = document.createElement('div'); productDiv.innerHTML = ` <h4>$
{product.name} - $${product.price.toFixed(2)}</h4> <button
onclick="addToCart(${product.id})">Add to Cart</button> `;
productContainer.appendChild(productDiv); }); } // Function to add item to
cart function addToCart(productId) { const product = products.find(p => p.id
=== productId); const cartItem = cart.find(item => item.product.id ===
productId); if (cartItem) { cartItem.quantity++; } else
{ cart.push({ product, quantity: 1 }); } updateCart(); } // Function to
update cart display function updateCart() { const cartContainer =
document.getElementById('cart'); cartContainer.innerHTML = ''; let total = 0;
cart.forEach(item => { const itemTotal = item.product.price * item.quantity;
total += itemTotal; const cartItemDiv = document.createElement('div');
cartItemDiv.innerHTML = ` <h5>${item.product.name} - $$
{item.product.price.toFixed(2)} x ${item.quantity} = $$
{itemTotal.toFixed(2)}</h5> <button onclick="increaseQuantity($
{item.product.id})">+</button> <button onclick="decreaseQuantity($
{item.product.id})">-</button> <button onclick="removeFromCart($
{item.product.id})">Remove</button> `;
cartContainer.appendChild(cartItemDiv); });
document.getElementById('total').innerText = total.toFixed(2); } // Function
to increase item quantity function increaseQuantity(productId) { const
cartItem = cart.find(item => item.product.id === productId); if (cartItem)
{ cartItem.quantity++; updateCart(); } } // Function to decrease item
quantity function decreaseQuantity(productId) { const cartItem =
cart.find(item => item.product.id === productId); if (cartItem)
{ cartItem.quantity--; if (cartItem.quantity === 0) {
removeFromCart(productId); } else { updateCart(); } } } // Function to remove
item from cart function removeFromCart(productId) { cart = cart.filter(item
=> item.product.id !== productId); updateCart(); } // Function to simulate
checkout function checkout() { if (cart.length === 0) { alert("Your cart is
empty!"); } else { alert(`Thank you for your purchase! Total: $$
{document.getElementById('total').innerText}`); cart = []; updateCart(); } }
// Event listener for checkout button
document.getElementById('checkout').addEventListener('click', checkout); //
Initial display of products displayProducts();
Intro to Data Types
Data is Everywhere!

All of these things can be represented as data:

 The grade you received on your first math test.


 The conversation you had earlier today.
 The decision you made to sit down and watch this video.
 And more...

Data is Important

It helps us:

 Understand the world


 Recognize trends
 Make educated guesses and
 Inform our decisions

Data and data types are the building blocks of any programming language
because they help us organize information and determine how our programs
will run.

In this lesson we will learn how to define and manipulate the primitive data
types of JavaScript.

 numbers
 strings
 booleans
 undefined
 null
Once you're familiar with these data types, you'll see how you can store data
in variables that you can reuse to manipulate data with your code.

Numbers
Numbers
Defining a number in JavaScript is actually pretty simple. The Number data
type includes any positive or negative integer, as well as decimals. Entering a
number into the console will return it right back to you.

3
Returns: 3
There, you did it.

Arithmetic operations
You can also perform calculations with numbers pretty easily. Basically, type
out an expression the way you would type it in a calculator.

3 + 2.1
Returns: 5.1

Arithmetic Operators in JavaScript

Operat
Name Meaning
or
Addition a+b Adds a and b
Subtraction a - b Subtracts b from a
Multiplication a * b Multiplies a and b
Division a/b Divides a by b
Modulo a%b Returns the remainder of a / b
Exponent a ** b Raises a to the power of b

The Modulo Operator

You are probably familiar with the basic operators, but you might not have
seen the % operator yet.
We use the modulo operator to return the remainder of a division operation.
This can be very helpful in a lot of programming tasks.

Before we move on, let's do some modulo practice.

Question 1 of 4

Match the remainder with each of these modulo expressions


These are the correct matches.
Modulo operation
3%2
Remainder
1
Modulo operation
8%3
Remainder
2
Modulo operation
6%3
Remainder
0
Modulo operation
1%5
Remainder
1

Question 2 of 4

Which of these statements is true about x % 3?

For any number y, the value of x % y is always less than y itself.

Question 3 of 4
Enter the expressions (one at a time) into the console and determine what
each expression evaluates to.
These are the correct matches.
Expression
2 + 10 - 19 + 4 - 90 + 1
Solution
-92
Expression
-20 + -19 - (-10) - (-1) + 24
Solution
-4
Expression
(10/5) * 4 - 20
Solution
-12
Expression
4096 % 12
Solution
4

Comparing numbers
What about comparing numbers? Can you do that? Well of course you can!

Just like in mathematics, you can compare two numbers to see if one’s
greater than, less than, or equal to the other.

5 > 10
Returns: false
5 < 10
Returns: true
5 == 10
Returns: false
Comparisons between numbers will either evaluate to true or false. Here are
some more examples, so you can try it out!
Comparison Operators

Operat
Meaning
or
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to

Question 4 of 4

Enter the expressions (one at a time) into the console and determine what
each expression evaluates to.
These are the correct matches.
Expression
43 > 47
Solution
false
Expression
12 == 17
Solution
false
Expression
3 <= 3
Solution
true
Expression
1 != 0
Solution
true

TIP: The values true and false have significant importance in JavaScript. These values are
called Booleans and are another data type in JavaScript. Later in this lesson, you’ll learn more
about why Booleans are so important in programming.
Comments
// You're about to take your first programming quiz!

Before you move onto the quiz, we want to talk about something you'll see
quite often throughout this course: comments!

You can use comments to help explain your code and make things clearer. In
JavaScript, comments are marked with a double forward-slash //. Anything
written on the same line after the // will not be executed or displayed. To have
the comment span multiple lines, mark the start of your comment with a
forward-slash and star, and then enclose your comment inside a star and
forward-slash / *…* /.

// this is a single-line comment

/*
this is
a multi-line
comment
*/
Some of the quizzes in this course might include comments that give you hints
or instructions to complete the quiz. Pay attention to those comments!

You may see comments that are used to clarify and document complex code.
This may improve readability, but it often makes more sense to reduce the
complexity by refactoring and simplifying the code. Simpler code is often
better code.

Alright, good luck!

Quiz: First Expression


Directions:
In the first-expressions.js file in the code editor below, write an expression that:
 uses at least 3 different arithmetic operators.
 equals 42.

Hint: +, -, *, /,* and % are possible arithmetic operators*

Running Your Code

Enter the following in the terminal:

node first-expression.js
Node.js(opens in a new tab) is an open-source backend JavaScript runtime
environment. That basically means that it will run your JavaScript code in the
terminal and return any output that is generated. We'll be using Node to run
the code in our workspaces for many of the quizzes in this course.

⚠️These workspaces will autosave your code -- but it can take a few
seconds.
If you try to run your code before the autosave occurs, you will see an error
like this:
ReferenceError: Cannot access 'variableName' before initialization
Wait a few seconds and try to run the code again.

Strings
Key Points to Remember About Strings

 Strings can be any combination of characters -- letters, numbers and even


emojis
 You must use matching quotes at the beginning or end of the string --
otherwise JavaScript thinks you are referring to a variable

TIP: It is correct to either use double " or single ' quotes with strings, as long
as you're consistent. The JavaScript Udacity style guide(opens in a new
tab) for labs and projects suggests using single quotes to define string literals
-- but your team or organization might follow a different style guide and prefer
double quotes.
Always follow your team's style guide
String concatenation
Strings are a collection of characters enclosed inside double or single quotes.
You can use strings to represent data like sentences, names, addresses, and
more. Did you know you can even add strings together? In JavaScript, this is
called concatenating. Concatenating two strings together is actually pretty
simple!

"Hello," + " New York City"


Returns: "Hello, New York City"
You will see other ways to concatenate and do even more with strings later in
this course. But for now, practice using the addition + operator.

Question 1 of 3

What's the result with "hello" + "world" ?

If you want to have a space in between two words, you need to explicitly add a space! It will not
be added automatically for you.

Question 2 of 3

What do you think will happen when you type "Hello + 5*10" into the JavaScript
console?
You might have thought that an error would happen. But, remember that
strings can be any collection of characters that are surrounded by quotation
marks. The + 5*10 are just characters inside the quotation marks, so the
interpreter will assume the whole object is a string, and output the result as a
string!

"Hello + 5*10"
output: "Hello + 5*10"

Question 3 of 3

What do you think will happen when you type "Hello" + 5*10 into the console?
You've just discovered some peculiar behavior in JavaScript. It’s called implicit type
coercion and it's a feature of JavaScript. JavaScript multiplies the 5*10 to become 50 and
then changes the number 50 into the string "50", so you're adding together the same data
type. This then gets combined with the string "Hello". You'll learn more about why this
happens later in this lesson.

Variables
Variables Allow Us to Store Data!
With variables, you no longer need to work with one-time-use data.

At the beginning of this course, you declared the value of a string, but you
didn't have a way to access or reuse the string later.

"Hello"; // Here's a String "Hello"


"Hello" + " World"; // Here's a new String (also with the
value "Hello") concatenated with " World"
Storing the value of a string in a variable is like packing it away for later use.

var greeting = "Hello";


Now, if you want to use "Hello" in a variety of sentences, you don't need to
duplicate "Hello" strings. You can just reuse the greeting variable.

greeting + " World!";


Returns: Hello World!
greeting + " Mike!";
Returns: Hello Mike!
You can also change the start of the greeting by reassigning a new string
value to the variable greeting.

greeting = "Hola";
greeting + " World!";
Returns: Hola World!
greeting + " Mike!";
Returns: Hola Mike!

JavaScript Has Three Ways to Declare Variables


- var, let, and const
In the example and video above, we used the keyword var to declare our
variable. When we use var we create a variable that is available in the global
scope -- which means it can be used anywhere in our program. We'll talk
more about scope later, but for now, keep in mind that globally scoped
variables are not a good practice.

Here's why: in a small program with just a few variables, it's easy to keep
track of the variables and avoid collisions. But when you are working on a
complex project or with a large team. It is very easy to inadvertently overwrite
an existing variable that is hidden in another part of the
program. let and const avoid this issue because they are only available in the
scope where they are declared. Again, more on scope later. For now,
remember:

Best Practice #1

Always use let or const instead of var

Which to Use - let or const ?


 Use let when we think that the value of a variable might change
let lets us to assign a new value to the variable name when needed.
 Use const when we think that the value of a variable is fixed
A variable declared with const cannot be assigned a new value. It's value
is constant.

So which should be your default choice? That's easy. Pick the one that gives
you more control: const. Using const means that your program will throw an
error if there is an attempt to change the value of the variable when the code
runs. If that is an intended outcome, you can go back and revise your code to
declare the variable with let. If you did not intend for the value to change,
congratulations! You've just discovered a bug that you can fix before it causes
any problems.

Best Practice #2
If you aren't sure, use const. You can revise your code later to replace
the const with let if needed.

Practice let and const

Try to answer these questions using what you know about let and const. If you
aren't sure, open up the console and run these code snippets to see what
happens.
What is the output of this code?

const dinner = "tacos";


dinner = dinner + " and " + "tamales";
console.log(dinner);
Correct! You will get a TypeError when you run this code because you are not allowed to assign
a new value to a variable declared with const

Question 2 of 5

What is the output of this code?

let dinner = "tacos";


dinner = dinner + " and " + "tamales";
console.log(dinner);
Correct! You used let to declare the variable dinner which allowed you to reassign it's value.

Question 3 of 5

What is the output of this code?

let dinner = "tacos";


const dinner = "tamales";
console.log(dinner);
orrect! You will get a SyntaxError when you run this code because you are not
allowed to re-declare a variable that has been declared with let. You'd get a
the same error with this code:

const dinner = "tacos";


let dinner = "tamales";

var still works and will remain working for the foreseeable future! 🤔
You'll see that we use var instead of let and const in some of the demo videos
in this course. While all of the modern browsers support let and const, var is
still part of the language. You'll see it quite often in legacy code.

Naming conventions
When you create a variable, you should write the name of the variable using
camelCase: the first word is lowercase, and all following words begin with a
capital letter. Additionally, aim to use a variable name that accurately yet
succinctly describes what the data represents.

// uses camelCase if the variable name is multiple words


const totalAfterTax = 53.03;

// uses lowercase if the variable name is one word


const tip = 8;
Not using camelCase for your variables names is not going to
necessarily break anything in JavaScript. But there are recommended style
guides used in all programming languages that help keep code consistent,
clean, and easy-to-read. This is especially important when working on larger
projects that will be accessed by multiple developers.

You can read more about Google's JavaScript StyleGuide here(opens in a


new tab).

Question 4 of 5

Which of these are good variable names?

The variables count and postLiked use lowercase and camelCase appropriately.
The postLiked variable has a descriptive name about what it represents.
The count variable is questionable and would depend on its surrounding
context. If the count variable was supposed to track the number of items in a
catalog, then a more descriptive name like catalogCount might be more
appropriate.

As for the other variables, thingy is a vague name that doesn't really describe
what 1 is the value for and firstname should be in camelCase.
Nice work! Even though some of these do not follow best practices for naming, JavaScript is
very lenient about naming. Following naming conventions is important to help
the people looking at the code understand it. The machine that runs it doesn't care.

Quiz: Converting Temperatures


LessonDownloads
To convert Celsius(opens in a new tab) to Fahrenheit(opens in a new tab),
you can use the following formula:

>F=C×1.8+32>>F=C×1.8+32>

Directions:
Use this equation and the variables fahrenheit and celsius to print the Fahrenheit
equivalent of 12°C.

NOTE: "12°C" reads as "12 degrees Celsius".

Running Your Code


Enter the following in the terminal:

node convert.js

You might also like