0% found this document useful (0 votes)
88 views26 pages

What Is Javascript?

- JavaScript is the most widely used programming language for web development. It allows for interactivity on webpages by handling events like clicks, taps, and swipes. - JavaScript can be used for both front-end development in web browsers and back-end development using Node.js. It is commonly used to create dynamic and interactive user interfaces. - Choosing an editor with features like syntax highlighting, code folding, and function navigation can help make JavaScript code more readable and writable.

Uploaded by

Mel Cui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views26 pages

What Is Javascript?

- JavaScript is the most widely used programming language for web development. It allows for interactivity on webpages by handling events like clicks, taps, and swipes. - JavaScript can be used for both front-end development in web browsers and back-end development using Node.js. It is commonly used to create dynamic and interactive user interfaces. - Choosing an editor with features like syntax highlighting, code folding, and function navigation can help make JavaScript code more readable and writable.

Uploaded by

Mel Cui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Ch7

Lesson1: JavaScript in Use

What Is JavaScript?

- [Voiceover] Okay, let's ask the most obvious question in this entire course. What is JavaScript? Let's get one thing out
of the way, JavaScript is not Java. JavaScript shares a lot of the same syntax as Java and has some other superficial
similarities for historical reasons, but they're very different under the hood. The internationally standardized name of
the language is ECMAScript, though it's still widely known as JavaScript as well. The point is JavaScript is its own
programming language entirely separate from Java. So let not the names confuse you.

Okay, so now that we know JavaScript is not Java, what is it really? It's the programming language of the web and
arguably, the most widely used programming language in the entire world. And when I say it's the programming
language of the web, I mean that it's the language that you use to program the web, that is, to make it do what you
want. These days, JavaScript is commonly used for what we call front-end development. That's any kind of programming
that happens in a web browser. When we talk about the front-end, that's something that happens in, you
know, Chrome, Internet Explorer, Safari, any of those things. If it happens in a browser, we call it the front-end.

For web designers, the bigger draw of JavaScript is the creation of interactivity. That means anytime you can click, drag,
tab, swipe, anytime you can interact with something on a webpage, generally speaking, that's going to involve
JavaScript in some way. There are certain kinds of interactivity that don't always require JavaScript but in general, if you
want a page to react to something the user does, JavaScript is the tool you want. Increasingly, you'll see JavaScript used
server-side or in back-end development as well, especially through Node.js.

JavaScript is also used to run databases like Mongo and can even be used to automate Photoshop. So JavaScript can be
used for almost anything on the web. Any kind of programming that you need to do on the web, JavaScript is your
friend.

Live examples

- [Voiceover] In this video, we're going to take a look at a few examples of JavaScript in the wild. We're gonna do this
just in case you aren't aware of some of the kinds of functionality that you can get by using JavaScript. Now, if you were
to look at lots of, say, social networks like Facebook or Twitter, JavaScript controls nearly everything on those
websites. Updating statuses, infinite scrolling, real-time updates of your feed, all that kinda stuff is controlled by
JavaScript. But we're gonna look at a couple of other examples here, that we can really take apart.

So I have two sites loaded here in Chrome. And I have the same two sites loaded in Safari with JavaScript disabled. So
first let's look at this Landon Hotel site. We have an inviting button that will scroll us down to the next section. And we
have some navigation here, and as we page through the site, it smoothly scrolls from one to the next. And these
different widgets update as we go. And it I scroll through it manually, you can see that I'm locked into the section where
the caption sort of bounces in and out.

As the scroll bar moves, I get that nice visual behavior. So that's pretty neat. Let's take a look at the same thing in
Safari with JavaScript disabled. Here we are, and already we can see that this background image for the first sort of
slide on the site, is not filling the entire browser window.That's because that sizing is controlled by JavaScript. It's making
each section of the site into a sort of slide. And then if I click this down arrow, I just jump directly there, no smooth
scrolling,so that's also controlled by JavaScript.

And then I scroll down, scrolling still works, of course, and the captions are still there. So there's a nice JavaScript free
fall back for each of these sections. I just don't get the same kind of visual enhancements. This kind of strategy is what
we call progressive enhancement,where you have something that works very nicely without JavaScript and then you add
onto that to get something even a bit nicer. So there we go. This events section seems to have broken down
completely without JavaScript, so that could maybe use a little bit of attention.

But overall, this site degrades nicely, when you have JavaScript turned off. Now let's switch back to Chrome, and look at
another one, H plus sport. This is another fictitious brand created for our courses. And we have a nice full page
background here. And then this middle section on the home page. On mouseover, these little slides bounce around. We
have a YouTube video down here in the footer. We have a search that discloses. So that's all pretty slick. Let's take a look
at the same site without JavaScript.

Okay, first of all, no background image whatsoever up here. I guess this must be a slideshow,and when there's no
JavaScript, no slideshow at all. Scroll down the page a little further, and we still have all the same content here, but
there's no mouseover behavior, and of course these are a lot smaller, they don't grow to fit the window. Same thing
with this slide down here.And this YouTube video completely falls apart. So we have two things going on here. First of
all, the embed code breaks down because we don't have JavaScript, but then also, the responsive re-sizing of the video
doesn't work either.
So as you can see, we can use JavaScript for a lot of different things, and you might even see it in areas that you don't
expect. And it's a good idea to use progressive enhancement where you can, so that your content is still accessible even
if JavaScript is turned off. Most people do leave it on, but it's still a good idea to plan for situations where JavaScript is
not available. Either because there's a bug in the code or because it's disabled.

Anti-use Cases

- [Voiceover] Now let's take a look at a few situations where maybe you don't want to use JavaScript, what you could call
JavaScript anti-use cases. First of all, anytime you're working with visual changes that involve the hover event or the
focus event, you can often make those kind of changes with CSS alone. CSS is aware of those events, so you don't have
to useJavaScript to respond to them. In the old days, we used to do things like image swaps, and moving sprites around,
or rollover menus, using JavaScript. You can do those with CSS alone in most cases now.

If you want to do basic animation on a page, CSS Transitions and Transforms offer a great dealof power without
JavaScript, and you don't need any serious coding at all. These are definitely worth exploring. JavaScript is still really
good for more advanced animation and you can, of course, use them together. So if there's a situation, for
example, where you need to be able to click something and have it animate, then you can use JavaScript in combination
with CSS Transitions to give you very smooth performing animations that will work on pretty much any web platform. If
you wanna learn more about that sort of thing, check out the course CSS: Transitions and Transforms.

Also, HTML5 form controls can be used instead of the custom widgets that we have, in the past, created with
JavaScript. This is especially important on mobile platforms, where you can get a custom keyboard on the mobile
device, depending on the type of form control. So those are some of the examples of times when JavaScript is not
necessarily appropriate and you can look at other modern technologies that will accomplish the same goals.

Lesson2: Writing and Debugging

Our friend, the Text Editor

- [Voiceover] If you're going to spend any time working with JavaScript or indeed any code whatsoever it's essential that
you have a good editor. Now, your choice of editor is going to be very personal, but I want to go over some features that
can help you determine what might make a good one. So we have a couple of ways that having a good editor can help
us. One is that it can make your code more readable. Some of the features that can make your code more
readable include syntax highlighting, where language keywords and other features are colored differently from the
words around them; code folding, which can take whole blocks of code and collapse them, which can make it easier to
navigate an very long file; and then function navigation, which is another way that navigating a long file can be made
much easier.

You'll get an outline or some kind of way of navigating through all the functions or symbols that are defined in your
source file. And then there are also enhancements that can make your code more writable, things like block
balancing. When you're writing code, you end up writinga lot of parentheses, curly braces, square braces, all that kind of
stuff, and a good editor can help you see what each of those delimited units contains. And then there's auto-typing. This
can help you write your code by typing out the closing html tags, say, or the closing brace in a block of code.

It can also make your code more readable by doing indentation for you. Now let's take a look at the difference
between a very simple editor and one that has some of these enhancements.So here I have a large JavaScript
library, moment.js, and I've opened it in TextEdit here on my Mac. If you're on Windows, the equivalent would be
something like Notepad. It's just the built-in text editor. And as you can see, the code is quite long. There's a lot going on
here, and Ihave absolutely no help at all. It is written nicely so it's still fairly readable, but everything is the same
color, it's very hard to tell the relationships between different parts of the code.

I really don't have a lot of help here from the software. Let's contrast this with a very simple text editor that is also free
and available for the Mac called TextWrangler. This is the same file, but already it's much more readable. Now of course,
if you're not very familiar with JavaScript this could still look like a bunch of nonsense, but as you start to become
familiar with JavaScriptyou start to recognize things like functions and this type of operator. The keyword this, var, all
that sort of thing. It's all highlighted for you.

Up here, there's a function navigator that shows me all the functions defined in the file, and as you can see, there are
tons of them. So I can jump down to any of them instantly. This also provides code folding, so over here in the margin
there's a little down arrow, and I can collapse that entire function. So if I'm working on this section of the code, and I
want to have these available but I don't necessarily want to work on setMonth and getSetMonth, I just want to work
here, I can collapse these so I can refer back to them if I need to see what's in there and then get back to work on the
function that I'm actually interested in.

So, there's lots of enhancements that even a very basic text editor like TextWrangler can give you. Here are a few
examples of editors that you might want to look at when you're getting into JavaScript development. The first is
TextWrangler, which is available only for Mac users. As it says here, it's the little brother to BBEdit, which is an editor I've
been using for what feels like my entire life. So if you're a Mac user, it's definitely worth taking a look at. Then I have
four more recommendations that are cross-platform. They're available for Mac, Windows, and Linux. The first is Atom,
which is an open-source editor brought to you by the same people that brought you GitHub.

One of the interesting features about Atom is that it's built on the same technology that powers your web browser, so
you can write plugins for it with JavaScript. There's also a course in the library called Learn Atom: The Basics which you
can check out. Another option is Brackets. It's cross-platform, and this one's brought to you by the same people that
bring you Adobe products. They have a version called Edge Code which is the version they're selling, and then the
editing component of it is called Brackets, and it's its own, totally separate app.

You can check out more on Edge Code and Brackets in the course Adobe Edge Code and Brackets: First Look. There's also
Sublime Text, which has been super popular among many of my friends in the web development community. I've been
using BBEdit too long to really get into it myself, but a lot of people really love it. You can use it for free, and it does have
a commercial license if you use it for a long time. You can check out the course Up and Running with Sublime Text 2 to
learn more about the previous version of Sublime Text. Most of the functions that are in Sublime Text 2 carry over into
Sublime 3.

And then finally, there's WebStorm, which is a bit of a step up from just an editor. It's actually an integrated
development environment. When I go from BBEdit, usually I'm jumping right into WebStorm. An IDE gives you even
more intelligence about a whole project that you're working on. It can scan all the defined functions and auto-complete
them for you, all kinds of really useful stuff. There's a free trial with this product, but it is commercial, so you'll need to
pay for it eventually. All of these examples will be a big step up from just a plain text editor like TextEdit or Notepad.

So I recommend you check them out and see which one you like best.

Browsers and tools

- [Voiceover] Now let's talk about the other essential tools when working with JavaScript, which is your web browser and
the Inspector tools that are built into your web browser. For now, you can just pick one. I'm going to give you some of
the options that are available, but you don't have to sweat the choice. Just start out by getting familiar with one and
seeing how you like it, and if you find deficiencies there you can move on and try one of the others. So first up, if you're
using Google Chrome, the Dev Tools are built in and all you need to do to access them is go to the View
Menu, Developer, and turn on the Developer Tools.

You can go straight to the JavaScript Console, if you like, and they'll pop up. In the current version, you have some
Settings in this little three-dot menu. I currently have these set up to dock on the right side of the window. Usually, by
default, they'll pop up at the bottom. And you can bring them out into their own window as well. If you're interested in
seeing what's happening with the latest version of Chrome, although it does get updated very often, you can check out
Chrome Canary, which, as it says on this page, has all the newest features.

It's meant for developers who are writing Chrome Extensions and that sort of thing, but you can check it out to see
what's coming up in upcoming releases of the Developer Tools as well.If you use Firefox, you can get to the Developer
Tools in the Tools Menu, under Web Developer, and then they're all available here. You can go straight to the
Inspector, and then there's the JavaScript Console, the Debugger, and so forth. There's also a separate version of
Firefox called the Firefox Developer Edition. It has some additional features that are of interestto developers that might
eventually make it into Firefox itself, but this is where they work on them.

So you can check them out here. In Safari, which is only available on the Mac, you have to do a little extra work to get to
the Developer Tools. Visit your Preferences, and then under Advanced, there's a checkbox, Show Develop menu in the
menu bar. With that turned on, you have access to the Web Inspector. And here it is. This is based on a very similar
engine to the one that's in Chrome, but they are different now. So you have your Resources, your Debugger, and your
JavaScript Console here.

The Bleeding Edge version of Safari is called the Safari Technology Preview, and this is a very nicely packaged up
way that you can see what's coming in upcoming versions of Safari. It's very actively developed, getting releases all the
time. You have to have a relatively recent version of OSX or Mac OS to run this, but if you do, it's definitely worth looking
at. And then finally, if you're a Windows user, I won't be able to show you the tools myself, because I'm working on a
Mac right now, but the tools are called the F12 Developer Tools, so named because you hit the F12 key on your
keyboard to make them come up.

These are available for Internet Explorer and for the newer Edge browser. So as you start to work with JavaScript, you're
going to spend a lot of time looking in the JavaScript Console for errors and other information, and all of these browsers
offer some very rich tools for taking apart your web pages and figuring out how to work with them. So I strongly
recommend that you start to get familiar with the tools that are built in to your favorite browser.
Tools in action

- [Voiceover] In this video, we're going to look at the JavaScript console to see what it can do for us. It's a very handy tool
for learning basic JavaScript in general, and with the debugger, it can give you great insight into your code. So let's start
by opening up the JavaScript console.You can do this either by using the View, Developer, JavaScript Console menu here
in Chrome, or as you can see, on the Mac I can type Option + Command + J or on Windows, Control + Shift + J to open it.

So let's try that. There we go. This opens up the Chrome Developer Tools opened to the Console tab. Of course, I have
many other options for things I can look at here. The Elements Inspector is very powerful for looking through the DOM
as an outline, but we're mainly going to concern ourselves with the JavaScript console for now. In the console, you can
execute JavaScript code immediately, and also inspect currently defined variables. So for example, if I type four plus
three here and hit Return, I get back the answer seven.

So that's executing some code, very, very simple code. But then also, I can look at currently defined objects. This
includes all of the global objects that are built into JavaScript, all of which are contained inside the global object
window. So if I start typing window and then a dot, I get this enormous pop-up menu with a list of all these defined
classes and objects. So if, say, I type set, I can see a couple of functions here.

Or if I type document, which is another global object, I can type a dot here, and then type, say, forms, type another dot
and I can see what's defined inside of that object. And it can go on and on. I can also inspect variables that I've
defined, and I can define variables right here in the console. So let's say I create a variable called x and assign it the value
of five. When I hit Return, the return value from this definition is undefined, but x itself is defined.

So if I just type x and hit Return, I get back its value which is five. This works for very simple assignments, but it can also
work for my own custom objects. Let's say I want to create myFriend as a new object which I can create with a pair of
empty curly braces like this. And now I can set a property on myFriend. We'll give myFriend a name. We'll say "Isaac,"
okay.And we'll also give myFriend an age.

And in the console, I can type an up arrow to get back the last line that I typed. So we'll say age is 35. Now when I type
myFriend and type a dot, I can see all of the properties that are defined on that object, including the ones I set myself,
age and name, and I can get back their values.Great. I'm going to clear the console using this Clear console button. I can
also define functions here if I want to.

This gets a little tricky because often you're going to define these on multiple lines, but it is possible. So let's say I wanted
to define a function called talkingDog, and I'm going to hold down Shift when I press Return to get line breaks without
executing the code. So I'll add a closing curly brace to delimit this function. And then inside it, we'll say alert("woof
woof"). And now when I hit Return, the function is defined. So I can start to type talkingDog. And if I just type it like this
with no parentheses following it, I'll just inspect it which will show me its value which is a function.

But now if I invoke it by adding parentheses afterwards, it's going to execute the code inside that function, and I get this
alert that says, "woof woof." Okay, we've seen this, but most of the time we're going to be creating our code in actual
pages. So let's do a little bit of that and see how we can interact with the console from our script files. Here's my script
that goes with this page. I just have a little bit of boilerplate code in here that we're not going to concern ourselves
with. Just know that everything is going to execute right away.

To log a message to the console, I can use console.log and then pass in a message. We can say, for example, "Hello
world." There's another method called console.error that I can use to make something really look like an error message
and tell me where it happened. "Oh, no, something went wrong." Okay, I'll save this and switch back to my
browser. Very good, now I can see my message here, "Hello world." And over here on the right, I can see what script file
it was defined in and what line it appears on inside that file.

So that's just a simple message. And then this one is an error. I get all the same stuff with a little bit of extra
formatting. And then if I disclose this, I can see where it was defined and what's called its call stack which is what
sequence of functions was called to get to this point. One more thing to mention. If I define a variable inside my
code, and I'll define a couple here. Let's call it variable1 and variable2, and we'll give them a couple of values.

We'll set variable1 to the number two and variable2 to the string "hello." Now in my console.log, I can output the
value of that variable. This can be very handy for figuring out what the value of something is at a certain point in your
code's execution. And if I'd like to find out the value of more than one variable at the same time, I could just pass more
of them in as arguments to this console.log function, like this. Just separate them by commas.

This is what that looks like. I've saved the file. Switch back and refresh. So here's the first one,and then on the next
line, it just outputs the value of each one in sequence. If you want to change this so you give yourself a little message to
see what this actually is, you could also pass in just a string and say, "This is variable2." Sometimes that can be helpful as
well. So I'll save that and refresh, and there you go. Now you've seen some of the basics of how you can use the
JavaScript console to learn about JavaScript.

As you become more comfortable writing JavaScript, please do check out my courseDebugging the Web: JavaScript to
learn how to use the debugger. Learning how to use the debugger can really change one's life for the better.
Getting help

- [Voiceover] Let's take a look through a few, mostly online, reference materials for when you're working with
JavaScript. Now of course, you can can just plug in any question you have into your favorite search engine and it may
you to Stack Overflow or other places where people are answering similar questions. But these are some more general
reference materialsthat are worth looking at. First up, is the JavaScript documentation that's available through the
Mozilla Developer Network. This is my favorite place to look, when I'm looking for just general JavaScript knowledge. It
documents the entire language, every object, every function that's built in, and has a whole bunch of useful example
code as well.

If you want to more fully understand the developer tools that come with the browser that you're using, each
manufacturer provides documentation for those developer tools. Here's the documentation for the Chrome developer
tools for Google's browser. Here's the information for the Firefox developer tools, which includes a little bit of
promotional information on the Firefox Developer Edition. Apple provides resources on Safari, including videos and code
examples. And then here's documentation on the whole platform if you're working with Microsoft Edge.

I also want to call out a couple more resources. One is this book, "JavaScript: The Good Parts".This is written by Douglass
Crockford, who is a long-time advocate of understanding JavaScript deeply, and this is a very highly opinionated
book. It's not too long, but it will go through the entire language and give you some very deep understanding of different
features of it. And it also tells you which parts, as the title says, are good, which parts are maybe, not so good, at least in
Crockford's opinion, and which parts are terrible, and should be avoided.

Reviews of this book will vary, because of how highly opinionated it is, but I found it to be really helpful when I was
learning JavaScript, and you may find it useful as well. And then finally, there's QuirksMode.org, which is a website that
includes a lot of different compatibility tablesand different kinds of information for what's supported in what
browser. Now as I mentioned, in this course we're generally not concerning ourselves too much with the features of
older browsers, so we're not worrying about really old compatibility stuff. But there are still differences here and
there, even among modern browsers.

But especially if you're working with backwards compatibility for older browsers, like Internet Explorer or
whatnot, QuirksMode is a very good place to look to get some help with those things. So those are a few options for
places where you can go to learn more about JavaScriptand the tools that you're going to be using when you're working
on your JavaScript.

Jargon

- [Voiceover] As with any piece of technology, JavaScript has a lot of jargon. Now, we're not gonna be able to
cover nearly all the jargon you need to become an expert in JavaScript in this course, but I do wanna give you an
overview of a lot of the basics that you'll need to make some sense of what we're doing. We'll start out with data
types. JavaScript is aware of lots of different types of data. You have numbers, one, two, three, all that kind of
thing. Everybody knows what a number is. You have strings, which are a sequence of words or characters.There are
Booleans, which refers to something which is either true or false, and then we have data types that are collections of
data.

Objects are the big ones in JavaScript. We have some built in objects, like window, which is called the global object when
you're working in a browser. Basically everything that's defined in JavaScript when you're working in a browser is part of
the global window object. Then we also have document, which is what you interface with when you're with the
document object model, which is something we'll talk about a little bit later, and a whole bunch more others.Objects
more generally, the ones that you can create yourself, and the ones that are built in,are said to have properties, which
are just pairs of keys or names, and their values.

Then we also have arrays, which are a type of data you see in a lot of different programming languages. In JavaScript
they're like a special case of the object. You can think of them like we do in other languages, though. They're basically a
sequentially-ordered list of items, and those items can be any of the other data types. JavaScript has variables. You may
remember variables from a math class in your past. But JavaScript uses them as well. If we think of JavaScript as a
language, like a spoken language, then you can think of variables as the nouns.

They're sort of like proper nouns. You take something, be it a number, or a sentence, or whatever, and you give it a
name. That name is a variable. There are also operators, which if we're keeping in the metaphor that we're going with of
JavaScript as a spoken language, are like verbs. These are how you can take things and make changes to them. JavaScript
has a whole bunch of these, and they can have all kinds of symbols. Here are a few of them. We have plus, equals,
double equals, exclamation point equals, and there are quite a few of these.

There's plus, which can be used for addition or for concatenating two strings together, that is, combining two
strings. There's the equals sign, which is used to assign data to a variable, and then there's the double equals and
exclamation points equals, which are used for doing logical tests to say is this equal to this, or is this not equal to this
other thing. Now we'll move on to functions. If we're stretching this linguistic metaphor to its absolute breaking
point, you could sort of think of functions as JavaScript's paragraphs.

They're also a data type in their own right, but they're a way to combine statements into single blocks that you can
reuse. If a function is inside an object, we call it a method. Arguments is another piece of jargon in JavaScript, and,
indeed, in most programming languages. In this case, an argument is how we get data into a function for further
processing. That's all it is. Most often you'll see them as named arguments, which means there are variables that are
definedin the context of that function, which we can then process.

Another piece of jargon is control structure. These are how we do logical operations, that is to say, if we want to do
something in some cases but maybe not others, or we wanna do something a certain number of times. Anything like
that is called a control structure. So, when we're talking about logical control structures, we have if, else, and switch. If
and else are usually used together, and then a switch statement is just another way of phrasing the same thing. Basically
it all means if certain conditions apply, do this.

If this other conditions apply, do that instead. And finally, if this other condition applies, do yet another thing. Then we
also have the notion of loops. There are a couple of main types that you'll use in JavaScript. One is the for loop, which
you'll see a lot, and then the while loop. I'm not gonna go into much detail on those right now, but just know that
they're both ways to do something over and over again until you need to stop. So that's a look at some of the jargonthat
you're going to be exposed to in this course. If you're interested in learning more about JavaScript, or you just feel like
you could use some more detail on any of these sort of jargony topics, you can look at my course, Introducing the
JavaScript Language.

Jargon: The DOM

- [Voiceover] There is a lot of jargon in JavaScript when you're talking about just pure JavaScript, not necessarily related
to a web browser. But when you start working with JavaScript in that most common context, that is on the web, you
have an additional layer of jargon called the Document Object Model, or DOM. The DOM is your way of accessing the
outline of a page. All the elements that you've written out in your HTML are collected up by the browser and laid out
visually and programmatically. And then the DOM is your programmatic interface that the browser provides you to
access all that stuff through JavaScript.

It's a collection of methods and properties that you can use to get into each of those elements.When you're working
with CSS to style your pages, that is when you're writing CSS selectors using ids, classes, tag names, all that sort of
thing, you're also working with the Document Object Model, just through a different interface. The DOM has a lot of
built in methods. The one you'll probably see the most often is called getElementByID, which is a method built into the
global object which is called document. When we say Document Object Model, it all comes from the built in object
called document and it has this method, that is a function that's built into the object, called getElementByID, which is
just like an id selector in CSS, a selector that starts with pound.

There're many other methods that you can use. getElementByID is the fastest of these three,but the other two are very
fast as well, and much more flexible. In addition, the Document Object Model provides a lot of properties for the page
elements it knows about. Some of the ones that we'll see in this course are value, which is used to get the value of text
fields and other form elements. Then there's checked, which is the property of checkboxes and Select boxes, which can
tell you, and I know this might sound surprising, whether they are checked.There's also classname and is, which are
properties of pretty much any element that will refer to whatever classes are set on that element and whatever the ID is.

Now, of course, this is all very much a simplification of everything there is to know about the Document Object Model. If
you want to learn more about this, check out the course JavaScript: Enhancing the DOM. But this should be enough to
help get you through the examples that we're gonna go over in this course.

Lesson3: Working with forms

Work with user info

- [Voiceover] Over the course of the next several videos, we're going to be working on this website for H+ Sport, a
fictitious brand we've created for use in some of our courses. They have a shop page on their WordPress site, and they
want to sell some products. What we're going to build is an estimator that can take the number of products they want
to order, the state that they're buying from, the shipping method, and then calculate the total. This is where we're
starting, but let me give you a little preview of where we're going to end up. So if I enter a few products and choose a
state, let's go with California, then when I click the Estimate Total button, I get a total estimate based on the price of
each product, the price of the shipping, and then I get a little summary down here of how we arrived at this total.

So back here on my start point, I want to show you what the HTML looks like. So here's my index.html file. It's quite long,
and there's a lot going on in here that is not of direct concern to us. It's just building up the site as it is. This being a
WordPress site, there are a lot of plugins that were loaded that load CSS files. Whole bunch of stuff here. What we're
mainly interested inis going to be a little further down the page after we get past the navigation and we get into the
actual HTML of the form where all of this stuff lives.

So I have these different blocks, which have a class called item, and then we have fairly semantic markup for each
product. And then down here, there's an ID for the summary areawhere we can estimate the order, choose the
state, pick the shipping method, and so forth.And then, finally, at the bottom of the file, if we scroll all the way down, we
have a script tag for loading our custom script file. And as you can see, there are quite a few other JavaScript files here
as well. And if you've never done this before, the way to load an external JavaScript file is just to use a script tag with a
source attribute that points at your file.

We'll look at that script file in a second. But scrolling back up to the actual content that we're interested in, I want to
point out that we have all these classes everywhere, and almost every item has an ID as well. This is important for CSS
styling, but it's at least as important for JavaScript. If it's possible, having IDs on the elements of interest is really
helpful. If your CMS or templating system doesn't provide them and you're not able to add them yourself, you can still
usually do the work you want to do, but it can take some clever filtering or selecting queries to get the items that you
want when you're working with JavaScript.

Also, where possible, it's nice to use HTML5 input elements, so you may have noticed in the browser that when I mouse
over each of these text fields, I get a little up and down arrow that lets me change the value. I'm in Chrome, and Chrome
has some special rendering for the HTML5 number input type. Instead of using a text field, I'm using number because
that way I can specify a minimum quantity. And then browsers that support it, like Chrome, you get these up and down
arrows, but then, also, I'm not allowed to type anything that's not a number.

Not every browser is going to give you this, but it's a nice feature for those that do. Now let's take a look at the script
file. I have a little boilerplate that we're going to use in all of our JavaScript, and I'll just give you a quick overview of
what this stuff is. All the code is wrapped in what's called an immediately invoked function expression, which is just a
way of protecting our code from accidentally being injected into the global namespace. If you want to find out more
about what this is and how it's used, there's a discussion on Stack Overflow that I've linked to here.

And then the first line inside the function is this use strict string, which turns on JavaScript strict mode, which helps us
avoid errors. It's not required, but I find it very helpful in making sure I don't make mistakes. There's more information
on how to use strict mode and what it means here on mozilla.org. So now we've seen our starting point and where we
intend to get to. So let's get started making some of these changes over the next several videos.

Text fields

- [Voiceover] In this video, we're going to start looking at how to get the values of different text fields. So, first of all, I'm
going to open up my JavaScript console so I can start executing some code right away. I can find that in Chrome in the
View menu under Developer, and then JavaScript Console. Clear out these little messages that I don't need. So I have a
few number fields which are text fields. I have a little text area down here for order comments.

So let's fill in a little bit here. My comments-- And then I'll add a few values in these different fields. Now I'm going to
inspect the element. I can right-click this and choose Inspect, and it pops open an outline. Let me make this a little
bigger. This is an outline of the current Document Object Model as rendered by the browser and known at this time. It
looks an awful lot like source code because, of course, that's where your DOM comes from. But this is what the browser
currently understands the DOM to be.

So it's like the source code, but it can change. And this is our interface for getting into the values of the form
fields. We're going to start by copying the ID of this first Basketball Sneakers field. So that's txt-q-bball. And double-
clicking the ID here in the inspector activates this text so I can copy it. Now, if I jump over to my console, I can use
document.getElementById. And the console is completing these for me as I type them to tell me what active methods
are availablehere on document.

And this is a function that takes one argument, which is the ID. So if I paste that in and hit Return, it gives me back the
element of interest. And if I mouse over it, it highlights it for me so I can make sure that I got the right one. Now that I've
done that, all I need to do is look at its value property like this. And the value is 2. It's a string, but it's a value of 2. And
this will work on any text field who has an ID.

So if I wanted to try this one-- This one is txt-q-jersey. These ID's, incidentally, I've structured them so that it's a text
field, an then I'm using q to indicate that it's a quantity, and then some unique identifier for that particular field. It's just
a naming convention. It can be anything you want. So I'm going to hit the up arrow to bring back the last thing that I
typed in the console.Then I'm going to substitute this new value, hit Return, and there it is. I get it back.

And this works on text areas as well. So let me inspect this. And here is its ID, txt-notes. And then back in the console, up
arrow, I'll paste in this ID, and there we go. So this works on every text field. Very handy. I'm gonna clear the
console. One other thing about the value property is that it's live. In other words, if you make a change to it, it will
update the form field right away.So, for example, if I go back to this basketball field, I can set its value as well, using an
equal sign to assign a new value to it.
So, if I wanted to change it to say, 15, I can do that and it updates right away. So just remember that you can read values
this way, but you can also set the values this way. I'm gonna clear the console again. There are some other ways that
you can access form elements if they happen not to have ID's. So, again, in the global Document Object-- There's also,
inside the global Document Object, there's another property called forms, which is a list of all the forms on the page.

This is an array. And to access the elements of an array, I use square braces and then the numeric offset starting at
zero. So, looking at this page, I seem to have just one form. So, presumably, if I were to use forms, index 0, then I should
be able to get that form. And if I mouse over this, nothing happens. Now, I happen to know there is another form on this
page.It's hiding up here. It's a hidden search field. So you need to be careful when accessing your forms in this generic
way using a numeric index.

The index you need could change, depending on how many forms you have, and in what order they appear on the
page. Fortunately, we can also access forms using document.getElementById if the form has an ID. So let me inspect
this. And I can see that this form does, in fact, have an ID. So let's copy that, come back to the console, and then I can
rephrase this as document.getElementById, and paste in that ID. So now I'm guaranteed to always refer to the form that
I wanted to.

Inside that form, I have an Elements property, which gives me all of the form elementscontained in my form. This is
another way that you can access the properties of your formwithout necessarily using their ID's if they happen not to
have any. It's also an array. So, if I put in a numeric index, I get back the value that's at that point. This will be the second
one. One final way that you can access your fields if you happen not to have ID's.

So let me scroll down and try one of the fields that we haven't looked at yet. I'm gonna right-click and inspect the
Shipping and Handling radio buttons. Here we are. Now, each of these inputs has a name property. When we're using
radio buttons, we can group them using this name attribute. And this is another way that we can access these form
fields. So, back here in the console, gonna hit an up arrow to get back my last line. And now, instead of using that
Elements array, I can use the name directly.

r_method was the name used on these. So, if I hit Return, I get back all three of them. So you have a variety of ways of
accessing these fields. By far, my preferred way is to usedocument.getElementById if I can. But if, for some reason, your
current HTML is not directly accessible to you because you're not on that team, or whatever the reason might be, you do
have other ways to get in there and try and find them. And we've seen that we can get text field values just using the
value property.

And we're going to move on and look at some of the wrinkles in other types of form fields next.

Select boxes

- [Voiceover] In this video we're going to look at how to access the value of a select box. So we're going to look at this
state field now. It's a select box with a few different values. And I'm going to open my console again. The way to access
the value of these fields in modern browsers is just as easy as it is for text fields. If I right click this state field to select
it in my web inspector, I'm gonna get its ID by double clicking here as hyphen state, and now in my console I can
use document.getElementBYId pass in the ID and look at its value.

Which currently is an empty string because, well, nothing is selected. If I select California and try it again, I get back
CA. Now notice the value that I'm getting is not the label that's shown here. Why is that? Back here in the elements
inspector I can see why. The structure of the options here in the select box are a label inside the option tag and then the
value is the value attribute.

So note that when you have those value attributes set for your options, those are the values that you will get back from
the DOM in Javascript. And just like with text fields, I can update the value of this field from Javascript the same way. So
if I want to make an assignment, I'll change this to just select again, and then I'll set the value to CA using the assignment
operator. There we go. It updates and changes to California. So, of course, if you work this way, you're going to need to
know what your actual values are.

But because you're processing these values yourself, you just need to look them up here to know what you're dealing
with. Let's switch over to the text editor for a minute. Here in my html file I'm going to scroll down to the form, and
we're going to see what happens when these values are removed. I'm just gonna remove a couple of them for now. So
before Select had a value of empty string, and then California had the value of CA. I'm gonna save this file, go back to the
browser, and refresh.

I'll clear my console messages here. And now if I hit an up arrow and check the value of this field, I can see that now
instead of an empty string it's literally Select. When there's no value attribute, the value that's contained inside the
option tags is what you'll get back. So this may or may not be desirable depending on the particular form that you're
trying to build. I know in this case because I'm also including the tax rate for the state of California, I wouldn't necessarily
want that to appear in my value.

If anything, I might like to just have California. So this would mean that I either have to strip offanything extra with
further form field processing, or I can just use the value attributes, as I'd set up before, so that my values are simpler and
easier to deal with programmatically. So back here in my html file, I'm going to undo those changes and re-save. There's
a couple more properties of select boxes that are useful especially when you're dealing with older browsers.So every
select box, along with having this value in modern browsers, has a property called Options.

And this is an array of all of the options. There's also a property called Selected Index. This gives you the numeric index
in the array of whichever option is currently selected, and we can use these together in situations where that value
property might not be available in certain browsers. So back here in my script file, I'm just gonna give you a little
sample of how we can use that. I'm gonna create a variable using the VAR keyword. Call it selectedIdx, and this would be
document.getElementById.

Pass in s-state, and then we'll retrieve the selected index. This will be a number. Then if we want to get the actual
value, we can create another variable called selectedValue, or whatever we liked. And this will be the same thing. And
then in the options array, we can use this selected index to retrieve that option and retrieve the options value. So as you
can see, this is way more verbose.

And it's much better if we can just simply retrieve the value like this. But you do have this option in situations where you
need it. So that's a look at how to work with select boxes.There's the easy way to retrieve their values, and the easy way
to set their values, and then the slightly more verbose way that you can use when you need it.

Radio buttons and checkboxes

- [Voiceover] In this video we're going to look at a couple of the other field types. Radio buttons, and checkboxes. These
have some special ways of accessing them with some new properties of interest. So I'm going to open up my
console, and I'll inspect the checkboxes first. So first I'm going to look for an ID on these checkboxes. Here's one on the
special gift checkbox. Very good. So I'm going to double click this and copy it's ID, then switch over to the console.

First let's try what we've been using so far. Document.getElementById. Pass in the ID. And then check the value. Here I
get back YES. Alright, we can clearly see that this checkbox is not checked. So what's going on here? What's going on is
the value attribute on this checkbox is yes, so I'm actually getting back the correct answer, I'm just maybe not asking the
right question. So the right question to ask is, is this box checked? If it is, then maybe I'll take some particular action.

The way to find out whether a checkbox is checked is to use a different property. So I'm gonna type in up arrow, the
property that I want is, of all things, checked. And this is a boolean. It's either going to be true or false. Currently this box
is not checked, so it's false. Now when I check the box, come back to my console, hit up arrow, to get this again, execute
it again, now it's true. This is what I really want to know when I'm dealing with checkboxes.

Is the box actually checked? And I can use this same checked property on radio buttons as well, but I'm going to use it in
a different way. And I'm going to inspect this pickup radio button first. With radio buttons it's a little different, because I
have a group of them, and only one value can be selected. So getting the value of the currently selected radio
button actually is meaningful in a way that retrieving a value is not so meaningful for a checkbox.

Each of these shares a method name. There are some other properties they share as well,they are all the radio type, but
what I want is the value of the selected radio button. Now, in the document object model, the property that I'm
checking is not called selected. Just as with checkboxes, it's called checked. As you can see here, by default, the pickup
method is checked. But it can be a little bit tedious to check each radio button individually, and ask, is this checked? Is
this checked? Is this checked? It'd be nice if there were a better way to do this all at once, just by asking the entire
group, which one of you is checked, and give me back the value.

We have a different function that can help us with that. It's also on the global document property, and it's called
querySelector. This is a relatively new property, supported well in all modern browsers. And it lets me use CSS syntax
to select elements on the page, the same way that document.getElementById lets me select items by their ID, with
querySelector, I can use CSS to make a selection using anything that's supported by CSS.

In this case, I wanna select the input whose name attribute is the one used by these radio buttons, which is
r_method. So I'm going to double click that, copy it, come back to my console, and an attribute in selector in CSS uses
square brackets like this. So I'll say name=r_method. And then I'm going to use a filter, or a pseudo selector in CSS, called
checked. So this CSS says, give me the input whose name attribute is r_method, and which is checked.

And there we go. I get back the pickup radio button. Let me change the selection. Now UPS is checked. Try the same
thing, and I get back UPS. And so now, if I tack on the value property here, I get back the actual value that I want. This is
much, much easier than it used to be,dealing with radio buttons before we had querySelector. There's an equivalent
method to querySelector called querySelectorAll, which will retrieve all the elements that match a particular CSS
selector.

So for example, if I wanted to retrieve all of those radio buttons, I can use querySelectorAll, like this, and then I get back
a list of all of them. And I could use a JavaScript loop to go over these,and look at the checked property individually, but
it's so much easier to use querySelector,and use the CSS3 checked pseudo selector like this to grab it. So now we've seen
some of the tools that we can employ when looking for the value of radio buttons and checkboxes.
Document.querySelector, and Document.querySelectorAll are extremely useful, quite fast, and as long as you're
targeting a relatively modern browser, you'll be able to use them all over your pages.

Change submission with events

- In this video, we're going to start looking at events, which let us respond to actions the user takes on our pages. With
this form, the action that we want to take is estimating the total after the user has filled out the form and submitted
it, and when those events are fired, we have the opportunity in our JavaScript to react to those events and do some
things. In this case, when the form is submitted, we want to be able to estimate the total, update this text field, and
showour little results area down here. As it stands, when the form is submitted, the page reloads, and the URL updates a
little bit, but of course, we have no JavaScript firing.

So what we need to do is called "adding an event listener" for the submission event. We're going to do that now. Let's
go to the script. To add an event in JavaScript, you use the "addEventListener" function, and this is something you can
add to pretty much any element on the page. And so what we need to do is select the form first, and then add the event
listener to the form. So let's use "document.getElementById", and then we'll retrieve the ID to pass into this function.

Switching back to the browser, I'm just going to inspect anything in this form. Go with this header. Here's my form tag
with the ID, "cart-hplus". So I'm going to double click that and copy it, switch back to my script. There we go. So I have
document.getElementById('cart-hplus').We're going to add event listener to it. This is also a function, and it'll take two
arguments. The first is going to be the type of event that we're listening for. In this case, we're adding the event
listener to the form.

And we want to listen for its "submit" event. There are many other event types that we could be listening for. The one
that you use is going to depend on the actions that you want to take,and what the item actually is. If it were a link, we
could say, "Listen for a click", or if it's a form field, we could listen for the change event, which is what happens when the
user updates a value, and then tabs over to the next text field, or what-have-you. With a form, we'll almost always
listen to the submit event.

So that's the first argument. The second argument is going to be the function that we execute when that event
happens. We can specify this in different ways. In JavaScript, you'll often seepeople pass in a function as a value, like
this. It's an unnamed function, so we call it an anonymous function, and then you can just write everything that you
want to execute right here in the body of the anonymous function. I'm going to do it a different way, using a named
function. We'll call it "estimateTotal", because that's the action that we want to take, and then I'm going to define the
function down here, estimateTotal, like this.

Okay, so far so good. But what we want to do is prevent the default action on the form from taking place, so that we can
execute our JavaScript. And you may remember the default actionis that the page reloads. We don't want that to
happen anymore. The only thing that we want to happen is for the form to calculate the estimate and update the page
in place. The way we do that is by passing in an argument to our function. Every event listener function makes
availablean argument for the event that was fired, and when we pass it in to our estimate total function,usually, we call
that argument "event".

You'll also sometimes see it labelled as "e" or "evt". We'll use "event". And so the power here is that it gives us
information about the event that was fired, and it lets us act on the event as well.And that's what we want to do
here. We want to prevent the default action by using a method built into every event called "preventDefault". We're
going to call that, so now when this form is submitted, nothing will happen except for what we define in our estimate
total function, which, for now, is just going to be a message to the console using "console.log".

"You submitted the form." I'll save the file, and now we can switch back to the browser and try it out. So I'll open up my
console and refresh the page. Clear out these messages. Now if I click "estimate total" to submit the form, the page does
not reload, we stay right where we are, and we just get our message. Of course, this is not a great deal of functionality at
this time, but nowwe've set up the structure that we can flush out later as we start making our calculations.

So that's an initial look at events. We've just added a submit event listener to our form, but you can use these
anywhere you want to respond to actions that the user takes.

Start to validate input

- [Voiceover] In this video, we're going to start looking at some ways to make sure that some fields are filled in, and
making some changes accordingly. In order to estimate this order total,of course I'm going to need to know how many
products of each type the user wants to order.But I also have this state field down here, which is required. Currently,
when I click estimate total and submit the form, I get no indication that I haven't filled this in. So we're going to make
some changes, so that the user must fill this in before the total will be estimated.

The first thing that we'll do is make sure that the field is not empty. Switching back to my script,here in my estimate total
function, I can get rid of my console message, and now I can look at the value of that state field and react if it's
empty. How do we do that? I'm going to use an if statement, which looks like this. If, parentheses, and then curly braces
indicating what I want to happen. So here in the parentheses, I'm going to fill in the condition that I want to check. And
what I wanna check is whether the state field is empty.

So I can use document.getElementByID and then pass in the ID of that state field, which I remember is s-state. We're
going to check its value, and then what I want to confirm is that it's not empty. If it is empty, I want to alert the user. So
I'm going to use the triple equals sign,which is the strict equality operator in JavaScript to check if it's an empty string. If I
want it to be a little but more permissive of different value types, I could make this a double equals. But in the interest of
avoiding errors, I like to use the triple equals sign if I can.

So if it's an empty string, I'm going to alert the user, and I'm going to use the alert function,which you might also
sometimes see as window.alert. We can phrase it just alert like this, and then we'll pop up the message please choose
your shipping state. Okay, I'll save this, and we'll switch back and try it out. Refresh the page, and now I'm going to click
estimate total.There we go. We get an alert that says please choose your shipping state, and now I can go back and
make my selection.

We can make this a little bit better. Along with just popping up the alert, I can set keyboard focus on that field, so that
the user can see immediately what they're supposed to do. In other words, we can force the browser to fire a particular
event. In this case, I want to fire a keyboard focus, so that that input field would be outlined and activated for keyboard
input. And the way that works is by selecting the element that I want it to activate, and then calling the focus method on
it.

Now as you can see, I've copy and pasted this document.getElementById a couple of times, so that's a good
opportunity to create a variable that I can use more than once. So we'll call this state equals
document.getElementById and then I can substitute this each time I use it. There we go. And the event that I want to
trigger is called focus. And there's a method on the element called focus as well that will trigger the event for me. So
now if I save this, and switch back to the browser, I can refresh, and now with this field empty, I can click estimate
total,please choose your shipping state, click okay.

And immediately, this is selected for me. Now I can use my keyboard, or otherwise just be notified that that's what I
want to happen. So this is much more usable. I know that I need to do this and now once I've selected a state, I can click
estimate total, and I don't get the alert anymore. With HTML5 form controls and many modern browsers, you have
other ways of making fields required as well. So let's switch back to my editor and open the HTML file for this page. I'm
going to scroll down, to the form, and go the state select box.

I can add the required attribute, which looks like this in HTML5, or like this in XHTML. And if I add this on to any form
control, and in browsers that support it, I'll get some help in the user interface without having to write a line of
JavaScript. Let me refresh this. I'll click estimate total and before my JavaScript executes, I'm prompted by the browser
to select an item from this list. Now not every browser supports this, and provides those kind of user interface hooks. So
we usually end up having to write code in our JavaScript to handle this sort of thing manually.

Checking values on the form and informing a user of errors and other issues is called form validation, in general. We're
not going to go to deeply into this in this course, but if you wanna know more, you can check out the course Validation
and Processing Forms with JavaScript and PHP. That will show you how to do validation on the front end as we're doing
here with JavaScript. And then how to do it service side as well using PHP. And so that's a look at how to make sure
that your required field actually is filled in by the user. And then how you can trigger certain events on your form
controls to activate them.

Disable a field

- [Voiceover] In this video we're going to enforce our requirement that the "state" field be filled out in a different way:
by disabling the "estimate" button when the page first loads. Right now, there's no indication other than this "required"
label that I have to fill it out before I can click "estimate total." So, what we're going to do is make sure that this button
can't be clicked before this is filled out. Let's go back to the script file and start writing some code. Currently I've added
an Event Listener to the form, listening for its submit action.

What I'm going to do this time is listen for when the page itself loads. So I'm going to copy this and create a new Event
Listener, only in this case, instead of listening to the form, I'm going to listen to the document itself, and the event that
I'm going to listen to will be DOMContentLoaded. Now there are different ways to listen for when a page is ready to be
acted on by JavaScript. Using DOMContentLoaded is considered a best practice as far as which event to listen to when
the page loads and you just wanna know is my DOM ready? If you want to check whether the resources that the page is
loading, that's images and other files are ready, you can use the "load" event, and there's other possibilities as well that
are different across browsers.

Trying to figure out when the page is actually ready to be acted upon is one reason that developers will often turn to a
JavaScript library like jQuery or one of the smaller dedicated libraries that specifically addresses this issue. But for our
purposes right now, dealing with just a standards-compliant series of modern browsers, we can just listen for
DOMContentLoaded, and we'll be okay. So what I'm going to do here is define an anonymous function and then we're
going to take some action when the page loads.

So actually, I'm going to move my Event Listener for the form into this function as well,because I don't wanna try and
add that Event Listener until that form is actually ready and processed in the DOM. So that's part one. After that's done,
I'm going to look at disabling the "estimate" button unless the "state" field is filled in. And because we're reusing this in a
couple of different places, I'm going to move my variable that finds that "state" box all the way up here.So now I can use
it here in this function and in my "estimate total" function as well.

Now that I have the state, I'm going to select my button. So I'll create a variable called "button estimate," and I'll use
document.getElementbyID and I'll pull its ID. Let's go back to the browser and get that. I'll right click the button and
inspect it. Here we go. BtnEstimate, so I'll double click that and copy it. Paste it in. And now, I have the two things that I
need. So first, I'm going to check the value on state.

I'm going to say if state.value is empty, I want to disable the button here. And just like check boxes have a checked
property, most form elements have a disable property. So in this case, I'm going to set that
property btnestimate.disabled to true. So when the page first loads, if state.value is empty, I'm going to disable the
button.

And if it's not, I'm going to re-enable it. So if I save this, switch back to my browser, and reload the page, Estimate Total
is currently disabled. Okay, here's the tricky part. I've actually done something that I didn't mean to do here because
now when I change this value, this button remains disabled. So we need to refactor this a little bit. What actually needs
to happen is when the page first loads, the button should be disabled right away, and then we need to listen for when
the value changes on that "state" field.

And then, disable or re-enable as needed. So let's add another Event Listener. We'll add it right here, and this event is
going to be added to the state pop-up menu. And the event I'm interested in is "change." So when that value changes,
I'm going to check it, and then enable or disable the button as appropriate. We'll just define it in line with an anonymous
function.Copy and paste this into my function.

I'll move my variable up here, so it's clear where I'm using it. And then finally, I'm going to immediately disable the
button when the page first loads. So btnEstimate.disabled = true. So once again, here's what's happening: page first
loads, we add our Submit Event Listener to the form, and then we grab the "estimate" button, and we disable it. And
then we add a second Event Listener to the "state" field. Every time it changes, we check its value, and if it's empty, we
disable the button.

If it's not, we let the button be re-enabled by setting disabled to false. Great. Let's switch back to the browser and
refresh and see if it works. Okay, the button is disabled, I can't click it, can't do anything here. There we go. Choose other
values, and the button remains clickable. Set it to an empty value, and it's immediately changed to disabled again. So
now I have a nice way of enforcing in the user interface that I need to select this before I can take any meaningful action.

Let's switch back to the script file, and I wanna show you one more thing. When we have something very simple, like this
block of statements, where I'm just asking, "Is this expression true?" And then reacting to that by setting another value
to true or false. I can phrase this a little differently on a single line. I can say btnEstimate.disabled = this expression. So, I
can put this in parentheses if I want to to make it a little clearer, but the idea is that I'm assigning to the disabled
property the value of this expression.

It's just another way that you'll see this kind of thing phrased sometimes, so I wanted to show it to you. But the way that
we phrased it up here is more explicit, and probably a little bit easier to understand. And so now our required "state"
field enforces our requirements right here in the user interface. Now we've seen how to take action when the page first
loads with the DOMContentLoaded event and how to disable form elements to help enforce the requirements of our
business logic: that this "state" field be filled out before we can calculate an estimate.

Retrieve all the data from the cart

- [Voiceover] In this video, we're going to collect everything that the user has input into our JavaScript file so we can
start fleshing out the calculation. So I'm going to inspect this Quantity desired field on the basketball sneakers, because
I'm going to need to collect all the IDs on all these fields so I might as well just have this inspector open as I collect each
one in turn. Let's start out with this one. Which I will copy, and switching over to my Script file, and now I'm going to use
the code-folding feature in my text editor to collapse this function, that I don't need to look at right now, so I can work
on my estimate total function.

Then down here, below, my validation of the state field, I'm going to start setting some variables for the various
fields. So I'm going to prefix all these with items. So the first one is basketball, so we call it item Bball, and that's going to
be document dot get element by ID, and then the ID that I just copied, and I'll retrieve its value property. And I'm going
to do this againfor the other three item fields. So I'm going to insert a comma here. When you're creating multiple
variables at the same time, you can separate them by commas like this.
So I'm going to keep a little bit of nice white space here, and just add them one right after the other. So let's retrieve
those other IDs as well. I'll just scroll down to the next item, and open it up. Here it is. Text Q jersey. And then the next
one, for these H+ Power supplements, is power.

I'll change the variable names as well, jersey, and power. So those are my quantity fields, and now I need the state and
the shipping and handling that the user has selected. So as we've seen, with state, which I already have in a variable up
here. Now for the shipping state, I already have a variable called state, up here, which I've used to select the actual input
box, so to collect its value, I'll create a new variable called shipping state, and that will be state dot value.

And then finally, I need the shipping method, which I'm going to call shipping method. And this one is that radio
button. So I'm going to use document dot query selector and this'll be the last one. And I'm going to use some CSS to get
to it. So let's inspect this to remind ourselves what we have here. This is a group of radio buttons that all share the R
underscore method name.So I could use input here, but it's also sufficient just to check the name attribute, using an
attribute selector.

Name equals R underscore method, and then I'll add on a checked pseudo selector, so it'll pull the shipping method that
I've chosen, and then I need its value as well. So now I've pulled all of these values into meaningfully named
variables. Let's log them out to the console and make sure that I got all this correct. So let's use console dot log, and
then each of these one at a time. I'll just copy and paste these right into the method.

The console dot log method can take as many arguments as you want, and it'll just log them all on one line right to the
console. Okay, I'll save this, switch back to the browser, bring up my console, and refresh. So let's add a few numbers
here. Let's go ten, twelve, fourteen, ordering a lot of items here, shipping to California, by US Mail. If I click estimate
total, here are my values.

Ten, twelve, fourteen, CA, and USPS. This is just what I was expecting. Okay, so now we've collected our values in the
code, and in the next video we'll start to make some calculationsacting on those values.

Total up a shopping cart

- [Voiceover] In this video, we're going to write the code that will calculate the estimate. In other words, get ready for a
little bit of math. So here in my script file I have my content loaded event listener collapsed. So I can work on my
estimate total function. Now I have my quantities of all these different items saved. I have the shipping state and I
have the shipping method saved.I'm going to need a few other things to calculate this. Along with the individual item
quantities,I'm going to need the total quantity of all the items for when I'm calculating the shipping.

Because my shipping cost is per item. So let's set that up here. My total quantity is going to beeach of these items added
together. I could put these all together. But I'm choosing to separate them just to make it a little more readable. I'm
collecting all the values here and thenI'm starting to act on them in this next group. I'm also going to need my shipping
cost per item.Which I'll call shippingCostPer. I won't set a value yet. And then I'm going to need my tax rate.Which I'm
going to set as a tax factor for when I do some multiplication a little later on.

And then finally, I'll give myself a variable called estimate which will be the final value of my estimate. So let's start out
by doing a basic calculation of the estimate based on the prices of the items I've purchased. So we'll say estimate = and
the way I'm going to calculate this, is the price of the first item multiplied by the quantity of that first item. And then add
on to that the price of the second item multiplied by the quantity of the second item. And I'm going to do this for each
item.

So this will be itemBball. I'll just copy and paste this a few times. Here's my jersey. And here is the power
supplements. Now what are the prices for each of these items? Let's go back to the browser and remind
ourselves. Basketball sneakers are 90. The jersey is 25. And the power supplements are 30. 90. 25. And 30. So that's my
basic estimate without the tax or shipping involved.

Let's put that in to the text field where the estimate goes just to make sure it works. So I'm going to use
document.getElementById. Then I'll retrieve the ID for that text field. And set its value to my calculated estimate. This'll
be what I'll do at the end of all my calculations. Let's retrieve that ID now. I'll switch back to the browser. Scroll down to
the text field. And right-click it and inspect it. Here we go. Text hyphen estimate.

So then I can switch back to my browser and paste this in. Now I'll save what I have so far and give it a try. I'll refresh the
browser. Add one of each of these. Just to keep it easy. So this would be 90 + 30 which is 120. Plus 25 which is
145. Choose my state so I can activate this button. There we go, 145. So far so good. Now I'm going to calculate my
tax. To refresh our memories, we can see that California is the only state where we're charging tax.

Any other state selection, no tax for now. It's seven and a half percent, so the way that I can do this is by taking the total
price of all of my items and multiplying it by a tax factor. For seven and a half percent, that's the same thing as
multiplying by 1.075. So what I want is my total price of all of these items which is currently my estimate multiplied by
my tax factor. And I need to set the tax factor based on the shipping state. So, if my shipping state is California.
I'm going to set my tax factor to 1.075. Otherwise, I'm going to set it to one. Now when I multiply a number by one, of
course I just get the same number back. Now the way I've written this, I don't necessarily need this else because this is
just serving as a default value. So I could just set my tax factor up here. There's my default value. And now I just change
it down below if I need to. When I'm using my tax factor, so let me save that in another variable as well.

Let's call this, totalItemPrice. And I'll set its value like so. I'll put this back in my estimate and then I can multiply that
total item price by the tax factor. This will give me a new estimate thattakes into account the tax. So let's refresh
again. And see how that works. One, one and one.Choose California. Estimate my total. That seems about right.

Choose a different state. And we're back to 145. Okay, everything looks very good so far. Let's check the shipping and
handling now. I'm going to need the total quantity of all these items.And then I'm going to multiply it by the price per
item. So I have my shipping cost per and I need to set the value of that based on the shipping method that I've
selected. I could do this with a series of if statements. If, else if. And so forth.

Where each time I'm checking for a different value of the shipping method. So I could say, pick up. Here. And then set
shippingCostPer to zero. Or, if my shipping method is USPS. That is the US mail. Set my shippingCostPer to two. That's
fine, but there's another way I could this that I wanna show you.

Which is a switch statement. A switch statement gives you a way to check for different values of a single variable. In this
case that'll be shipping method. And the way I do that, is my creating a series of case blocks. So in the case where
shipping method is USPS let's say. And then I add a colon. And my case block is terminated by a break. Unlike other parts
of JavaScript, instead of using curly braces, this is the syntax. Case, a value, colon and then a break statement.

Anything that's included in this case block will be executed in this case. So what I want to do is set my shippingCostPer to
two here. And then if my value is UPS. Set my shipping cost to three. Now I don't have a default value up here. I could
set it to zero here. But the switch statement also includes a way to do this. I could explicitly state pickup here. Or, I could
make this my default.

Which is specified by a default case just like this. And in that case, I would set my shipping cost per to zero. Because the
only other value here is three or zero. Now that I have my shipping cost, I can use my total quantity and multiply it by my
shipping cost per item to get my total shipping cost. So I'm going to add one more variable up here just called
shippingCost.And insert my calculation below the switch statement. ShippingCost = shipping cost per itemmultiplied
by the total quantity.

Right here. And so now my estimate is the total item price multiplied by its tax factor. Because that's the part that takes
tax into account and then add on my shipping cost. And that should be my total estimate. Let's give it a try. I'll refresh
the page. One of each of these. California and let's use free for now. This looks about like what we had before. I'll change
it to US mail.

Suddenly we've gone from around $155 to well over $300. And that's by adding two dollars per item which I would
expect to be six dollars. It's a lot more than that. So clearly we have a bug, there's something influencing the way that
this calculation is coming through that we're going to have to sort out to make sure that this estimate is calculated
correctly. And we're going to deal with that next.

Explore and fix type errors

- [Voiceover] When calculating our estimate, we are getting some unexpected results. To recap, if I put it a quantity in
each of these fields. Choose a state. Choose non-free shipping and handling. And then click estimate total. I get a total
that's quite a lot higher than it should be. Only ordering one of these items, that's $145 plus two dollars per item. That is
definitely not $367. So we have a bug. And it's related to the type of data that comes out of these fields when I collect
their values.

And then what I'm subsequently doing with them with the operators. Let's go back to the code and take a look. So down
here where I'm collecting the quantities of each item, I'm pulling the values using the value property. And then I'm
adding them together to get my variable total quantity. I'm going to copy these lines into my JavaScript console and
execute them so we can see what we're actually getting back and what impact that has on my total quantitycalculation
down here. So let's copy these lines. And switching back to the browser I'm going to open the JavaScript console.

Clear those out and paste this in. Okay, what's immediately returned is undefined. But we don't have to pay attention to
that. What I wanna know is what the actual values are now so,itemBball for example. If I start to type that it auto
completes and I can hit return to see its value which is one. However, it's a string. It's still limited by quotes. So what I'm
getting back from each of these fields is a string. And here's what happens when I add strings together. Like this.

Instead of three, I'm getting 111. That's not right at all. So what I need to do, is tell JavaScript thatthese are not strings,
they need to be numbers. And I have a built in function that can help me do that. So up here where I'm pulling in all
these values, I need to convert these strings in to numbers. And the function that I'm going to use for that is a built in
function called parseInt.And what this built in function does, is take a value and then figure out what its numeric
equivalent is.
Now in the case of a string that contains a digit, it's pretty easy. It just converts it from the string into a number. And I'm
going to do this to each of these quantities. Now it's considered good practice when you're using the parseInt
function, not only to just pass in the value but it can take a second argument called a radix, which means what base are
we operating in. The default is base 10.

But it's still a good idea to make that explicit. Just so we know exactly what we're going to get.And to be a little more
precise. So now that I've converted all these to numbers I should get a much more reasonable result. Let's switch back to
the browser. And I can close the console.And refresh. One of each item. Choosing the old state. Change my shipping and
handling method. 151, that's much better.

So this is something that you're gonna need to pay attention to in JavaScript. What type of data are you actually getting
back from different form fields, or from different calculations that you make. And then, we're you're operating on those
values later you might need to convert them from one type to another. Or you could get unexpected results, especially
when you're using the plus. The plus operator will add numbers together but it'll concatenate strings together. So don't
get burned. Make sure you know what type your data is. One other thing I'll mention here.

You can use what's called the alternation operator. Which is two pipes like this. To set a default value for your
variables. In case parsant doesn't always return what I'm expected to depending on the way it's implemented by a
particular browser. I might not always get zero if the field is empty. So I can say, if I don't get back something reasonable
here, give me zero instead. And I want that to happen for each of my quantities. Likewise, if my shipping method is
something that I don't expect I can make sure that it's a blank string.

Setting default values like this can sort of save you from yourself if you happen to mistakes in your HTML or somewhere
else in your code. Alright, so I have default values for each of these.Now the only other thing I want to do, back here in
my browser. I'd like to format this estimateso it looks more like a dollar amount. So here's what I'm going to do. Scrolling
down to where my estimate is calculated, I'm going to make the whole calculation and just enclose the whole thing in
parenthesis.

And first I'm going to add a dollar sign to the front of it. And once again I'm using the plus operator which in this
case, I'm starting with a string so the whole thing is going to turn in to a string. But only after this has been evaluated as
numbers. And then, I wanna make sure that this number only has two decimal places. So it looks like dollars and
cents. And there's a function for that as well. Called toFixed. And this is part of the built in number class. And basically I
can call it on any number.

So once this number is calculated, I can say toFixed and then pass in the argument. Two for how many decimal places I
want. This will take care of basic rounding for you. So now if I switch back to my browser and refresh one more
time. One, one and one. Choose a state.$151. If I have tax, let's try it again. 161.88. All these numbers look very
reasonable indeed. So as we've seen, you need to be careful about the type of data that you're operating on when
you're working with your calculations.

And another thing that's worth noting is that there's nothing in particular depending on the browser that could stop
someone for putting in complete garbage in some of these fields.They can try and type a bunch of letters or who knows
what else. So you wanna be careful and use sensible default values for all of your data to make sure that you will get the
expected results once you operate on the data later on. That process is called sanitization. So now we're done. We've
calculated our estimate correctly and now we're just going to need to update thissummary area that tells us a little
more about how this estimate was calculated.

And we'll do that next.

Get and set with innerHTML

- [Voiceover] We have just one more main task to complete this estimator. Down here where the total is shown, I wanna
show a few lines down below it that help illustrate how we got to this total. We're gonna show the total number of
items, the total shipping cost, and the tax that we were charging. We're going to look at a couple new DOM properties
that will help us do this.So let's switch back to the code. We're going to collapse this function, and then down at the
bottom of Estimate Total, here's where I'm showing the estimate.

And now what I want to do is update the results area. So I'm going to have another document.getElementById. We'll call
this results. And then I need to get the id for that area that I'm going to be updating. Because this area is empty and
this Estimate Total button is disabled,I'm going to inspect the text field. That will get me close, and now I can see it
here. The id is results. So I'm going to copy that, come back, and paste it in.

So now I've saved a reference to it, and the next step will be updating its contents, and I have a couple different
properties that I could use to do this. One of them is called innerHTML, and the other is called textContent. Let's see
what those look like in the browser. This area is empty right now of course, so let's select something else. Let's grab this
little footer here. I'll inspect this, so I can see it has a class which is fright, which I'm assuming means float right.
And it's inside the credits section. Alright, so we're going to select that here in my JavaScript console using
document.QuerySelector, and we'll use these classes in combination to make sure I get the right thing. This'll be the
fright class inside the credits class. That looks right, very good. Okay, so now that I've selected it, I can look at its
innerHTML property, and I get the exact contents with the HTML tags of what's inside here.

Likewise, I have textContent, which basically gives me the same thing, but with all the tags stripped out. And as with
many other DOM properties, you can get the values from an element using them and you can also set values back into
them using the same ones. So, if you're going to include HTML tags, you can use innerHTML, and if you're just writing
text, you can use textContent. Let's give this a try. So again, what I'm going to do, is show the total items, the total
shipping cost, and then the tax, one right after another.

So, I'll say results.innerHTML because I'm going to need line breaks in between each of these.Results.innerHTML = 'Total
items:', and then I'll concatenate onto that the total number of items.In other words, my total quantity, which is right
here. Okay, now I'll copy and paste this a couple of times. Next will be my total shipping cost, I'll just say Total
shipping, and then my shippingCost is right here.

And just like with my estimate, I wanna show this with a $, and with the right number of decimal points. So I'll use
toFixed, just like I did up here. Very good. And then finally, the Tax. And for this, I'm going to need a little bit more
math. I could just show the taxFactor, but that would be 1.075, and that's not really what we wanna show. We'd rather
show 7.5%. So, how can we take our Factor and get to that? First of all, we could subtract 1.

So we go from 1.075 to just 0.075, and then we can multiply it by 100. I will move the decimal point two places to the
right, and give us 7.5. So I'll enclose all of this in parenthesis as well to avoid confusion, and now I can use toFixed one
more time if I want to, to give me two decimal places, which might be appropriate for regions that use, say, 7.25, 7.25%,
that sort of thing.

And then I can also append on a percent sign to make it absolutely clear that that's what we're showing. And why not
also show the state, one more time here. So we'll add that in parenthesis. And which state was that? ShippingState. Now
you'll notice that the way I'm doing this assignment, I'm just using the equals sign every single time. So I'm just gonna be
reassigning the same thing over and over again. Which means that when I'm done, it's only going to show the tax.

If I want to have each of these concatenated on, I have a couple of different ways I could do it.The very easiest is to
change this operator to +=. This is basically the same thing as if I were to write out this in long form. Results.innerHTML
= the current results.innerHTML plus this new thing. So as you can see, that's a little bit long, and it's much easier to just
use the += operator as an alias. And then finally, to make sure that these all appear on separate lines, I'm going to
concatenate on a line break tag.

So I'll copy this to each line. Okay, I'll save that, and let's try it out. Refresh. Order a few products. Set the tax. Estimate
the Total. There we go. So I ordered three items, and that's what's showing here, three times two is six, and the tax was
California, which is 7.5%, if I switch to Illinois, 0%.

Exactly so. So now we've seen how we can use the innerHTML property and the textContent property to set the
HTML or the text of an element on the page.

Challenge: Add and use more fields

(cymbal burst) - [Voiceover] Things are going very well for H+ Sport. So well, that they're going to add a new store. This
new location is gonna be in Seattle, Washington, and they're going to start selling a new product on the Shop page as
well. So here are the instructions for the Challenge. We'll call this In with the New. There's going to be a new store in
Seattle, which means that we're going to need to start charging 6.5% sales tax if someone chooses Washington as their
shipping state.

We're also going to add this new product, H+ Sport Mineral Water. It's fizzy, and we'll charge 4$ a bottle for it, so you're
going to need to update a couple of things. First you're going to have to update the HTML file to include the state and
the new product, and then you'll need to update the JavaScript, where you can update the estimate calculator to
account for these new parameters. I recommend maintaining a similar structure to what's already there for the
HTMLwith the same classes and similar IDs to make sure that the styling stays consistent and that it's easy to follow as
you're starting to put it together.

This should take five or ten minutes. Good luck.

Solution: Add and use more fields

(electronic swooshing) - [Voiceover] Let's take a look at my solution to the In With The New Challenge. First of all, we
have the H+ Sport Mineral Water product here, it is fizzy, and it's four dollars a bottle. Everything looks pretty much the
same as the other products. That is good.Down here in the State select box, I've added Washington at six-and-a-half
percent sales tax.So let's try it out. Two bottles of the Power Supplements and two bottles of the water.
So this would be 60 plus eight, $68, and then we'll get the six-and-a-half percent tax for Washignton, and use UPS for the
shipping. $84.42, that's $12 worth of shipping at $3 an item,four items; that looks good. So everything checks out. Now
let's take a look at the markup and the JavaScript. First we'll look at the HTML file. I've taken the liberty of scrolling
down to the section of interest here, and now after the Power Supplements, I added the Mineral Water, with all the
same HTML structure.

All I changed was the ID, which is used on the label and here on the input field, using water instead of power. And then
for the State select box, we have Washington with a value set of WA, the state abbreviation for Washington. Okay, that's
everything in the markup. now here's the JavaScript. I'll close up this EventListener up here and just look at the
estimated total function. So I've added the itemWater variable here, that collects the value from the water text field and
then does the same parseInt that we did on all the other fields.

I've also added a little bit of white space, which is generally perfectly safe in JavaScript. Then I'm added it onto the
totalQty and the totalItemPrice calculation, again, with a little more white space. And then for the shippingState, we're
checking it here as well, and using a new taxFactor of 1.065. With those changes in place, you have everything you need
to make this work with the new product and the new state. So that's one possible solution. Of course, there are many
you could've employed, and you found the process of getting there enjoyable.

Lesson4: A Matter in time

Use JS to tell time

- [Voiceover] Over the course of the next several videos, we're going to be working with date and time in JavaScript. This
will let you create things like calendars, clocks, and do other functions on your pages that are time sensitive. So we're
looking here at the website for the Landon Hotel, a fictitious hotel with a website we've created for other courses. And
they have an event calendar. If I scroll down a little bit I can click events, and scroll smoothly right down to their event
calendar.

Here are some of the upcoming events. Over here we have this NOW region, which has nothing in it at the moment. But
they'd like to have a clock, so we can always see what time it is. I'm going to right click this so we can inspect it, and see
what it looks like. So, we have a container with an Id of clock, and we have this label, and then an empty div with an Id of
current time. There's a JavaScript file attached to this page we can work with as well. Let's take a look at that.

So far, there's nothing in other than our boiler plate immediately invoked function expression,and our switching on of
strict mode. So when the page first loads, we're going to want to set the time in that little region. So let's add an Event
Listener when the page first loads. We'll use document add Event Listener, and the event we'll be listening for will
be DOMcontentLoaded.And then we'll use anonymous function, like this. I'll back this out.

Like so. So the next thing that we need to do is set the content of that little box. We can do that using inner HTML, or
text content. I might end up using HTML for this, I'm not sure yet. So we'll start there, and then if it ends up being plain
text later, we can update it. So first, I'm going to get the region where the current time will live. I'll just give that a very
simple variable name of 'c,' and use document.getElementById, and then the Id was 'current-time.' We'll just hard-code
something for now, so we'll say c.innerHTML = '1:00 PM.' That will work.

Let's go back to the browser and reload the page. There we have it. Alright, so far so good. But of course it's not the
actual current time, unless I got really lucky. So, how do we get the current time? The tool we use is the built in date
object, and the way we use it is by creating a variable, I'll call it 'd' for date. And invoking the date object's
constructor. The way you do that is by using the new keyword, and then calling the date object as a function.

And in this case, I'm calling it will no arguments. When I call it with no arguments like this, it gives me the time now, and
it gets that time from the machine where it's running. Specifically in this case, from my web browser on my machine. So
whatever time it is, right now, on my computer is what will be shown there. But having created this variable doesn't
actually do anything for me yet. It just gives me the time in some kind of representation that's internal to
JavaScript. What I need to do, is convert that into a readable time that I can use on the page.

The simplest method for doing that, and a good place to start for us, is called 'toTimeString.'Which we call as a method
on our new date object. So now, I'll replace this hard-coded time with my TimeString. Okay, let's switch back to the
browser, and reload and see what that looks like. Alright, it is not exactly nicely formatted, but it is a real time.

Now I could do some formatting on this. Maybe lop off the time-zone, this offset, but I'd still have this in military
time with seconds and everything, and I don't think I really need that. So coming up, we're going to explore some of the
other methods that the dataobject offers that can give us something that will be a little more readable. But this is a good
starting point, and it's an easy way to make your page self-updating without any service-side interaction.

Get pieces of time


- [Voiceover] In this video, we're going to look at some of the other methods that are availableon the Date object, so we
can format our time a little more nicely. So I'm going to jump down to the Events Calendar. And then the page first
loads, I get this new time. Let's open the JavaScript console and take a look. So what we've been doing is creating a
variable and instatiating the Date object. Once I've done that, I have access to a whole bunch of methods.We used
toTimeString previously, which returns this, which is what we're inserting into the HTML right here.

Now, as I mentioned, to re-format this, I could just chop off some of the end using, say, the JavaScript substring
method. This method takes the arguments of the starting point and the end point within the string, starting with zero
and going as long as the string is. So if I wanted, say, these characters, I could go up to, I think it's about eight or so, and
that would lop off all of this business. But it's a lot nicer just to grab the actual pieces that I want and string them
together.

So how can we do that? I'll clear my Console, but my variable d is still defined. So I'm going to type get, and that shows
me a lot of methods that are available here. Date, Day, the FullYear, Hours, Milliseconds, whole bunch of stuff here. So
let's take a look at getDate. Today is the 16th of June, and so that's the date. Likewise, if I wanted to get the Month, I
need to call this with its parentheses, I get 5.

Now as I said, this is June, but as with a lot of things in JavaScript and other programming languages, you start counting
at zero, not one. So instead of Month 6, June is represented as Month 5. But I don't need the month for this Time. I need
things like the hours, and there is a method getHours, which is 14. This counts the Hours using a 24-hour clock instead of
going zero to 12 and then zero to 12 again. So what I'm looking for here is just the hour and the minutes, and then we
can format them as we like.

So I'll use getHours, and then getMinutes. Great. 14, 43. Let's switch back to the code and actually use these
methods. Here I have d.toTimeString. We can change this to getHours, and then we can add a time separater here, and
call this again, using getMinutes. If I save this, switch back and reload, now I have 14:46.

If I want to reset this to a 12-hour clock, I'll wrap this in parentheses to avoid confusion, and then subtract 12 from it. If I
refresh, now it's 2:47. Now, of course, I don't necessarily alwayswant to subtract 12, because before noon, the hours will
be less than 12, and then I could end up with numbers like negative 2:47. That's not right. So let's make this work
correctly. I'm going to calculate my hours separately, ahead of time. So I'll create a variable here called hours.

We'll set it to getHours. Then afterwards, I'm going to check if hours is greater than 12, and if it is, I'm going to subtract
12 from my value of hours. So I could say hours = hours - 12, and I can put this all on one line like this if I like, or if you
find it more readable, you can do it like this, inside the curly braces. So hours = hours - 12, or I can rephrase this using
the -= operator,which is similar to the += operator we've seen before.

So if hours is greater than 12, we'll lop off 12, and so we'll never see a 13 or an hour greater than 12. If you're thinking
ahead here, you may be wondering what happens when the clock strikes midnight. That's another edge case that we'll
be dealing with a little later on. And so now I'll put my hours in here, save the file, and switch back. Refreshing, you can
see that now it's 2:52 in the afternoon. Great. That's working fine. So now you've seen some of the methodsthat are
available on the Date object to give you different components of the time.

And there are going to be instances where you're going to need to reformat them, even after you extract just the piece
that you want, because the representation of that number in JavaScript might not be exactly what you want when you
bring it into your page. But there's quite a few options and a lot of flexibility.

Use timers to update the page

- [Voiceover] In this video we're going to look at window timers, which let you schedule the execution of code for
later. Scrolling down to the events section, here's my time. Now what I'd like this to do is update every so often,
probably every second or every minute, something like that, so an accurate time is always shown. Right now, it's only
done when the page first loads.So, we're going to use window timers to make sure it's always accurate. Switching back
here to my code. I have two window timer functions that I can use.

One of them is setTimeout. The other is setInterval. We'll look at setTimeout first. If you've looked at other people's
Javascript code, odds are you might have seen this before. It's very commonly used. This function takes two
arguments. The first is the function that you want to execute at some later time. And then the second argument is how
much later you want it to execute. So, let's say when the page loads, I want to update the time a second later. So let's
package up my time updater function down here.

We'll name it, call it updateTime. Just wrap everything in curly braces. Indent it, and then to make sure we can see the
updates when they happen, I'm gonna tack on d.getSeconds, so we can see the current number of seconds. And then I'll
update my setTimeout function. So we have updateTime and then the amount of time later, which I'm going to fill in as
1000.Which is 1000 milliseconds or one second.

So now I'll save this and switch back to the browser. I'll refresh and a second after the page loads the time updates. This
is fine and that function is quite useful for when you want to schedule things for later. But if I want this to happen every
second, it wouldn't really make much sense to keep doing this over and over and over again. Setting longer and longer
times into the future. This is where setInterval comes in, setInterval is called exactly the same way.

Only instead, this function will be called every 1000 milliseconds, in other words every second.So let me save this and
switch back to the browser. I'll refresh and I'm going to sit here twiddling my thumbs waiting for something to
happen. There's a problem here. This is updating, but it's not updating with the current time. And the reason is that my
update time function doesn't actually pull a fresh time every time it executes. So let's bring this down into my
updateTime function.

Now every time we pass through this, we'll get a new time and update it. I'll switch to the browser and refresh
again. There we go, now we have a clock that actually seems to be running, very nice. Now we don't actually need the
seconds to be displayed here. We've proved that it actually does work but how about instead we change it so it
works like a lot of clocks do where the time separator flashes every second.

Let's switch back to the code here and I'll make that happen. So I'm going to strip off this getSeconds business off the
end here. And so what we'll do this first time through is we'll change what the separator is. It can either be a colon or
let's make it a space. And what we're going to do is look at the seconds and if the number of seconds is even, we'll make
it a colon.And if the number of seconds is odd, we'll make it blank. So that way it will alternate between a colon and a
space.

How do we do that? Let's set a variable for the separator. We'll call it sep. And we're going to set it to some value. It's
either going to be a colon or a space. So we'll start with this and then we can say, is the current number of seconds even
or odd? The way we can do that is by using the modulus operator. So we'll say d.getSeconds, that's the number we're
going to check. And then the modulus operator is a percent sign.

And so what we do is say, if we divide this by two, what's the remainder? That's what the modulus operator does for
you. And in this case because we're dividing by two, the remainder is either going to be zero for an even number or one
for an odd number. So we said that we're going to make this a space if it's an odd number. So if the remainder is one,
we'll reset this to a space, like this. And then we can replace our hard coded separator here with our calculated
separator.

Now save this file and switch back to the browser and reload. There we go. We have a time that shows the hour, the
minutes, and it has a nicely flashing separator here. Now if you look closely, you can see that these numbers are shifting
around a little bit as this time separator flashes. So we'll want to fix that later. But this is a very good start.

Polish the clock

- [Voiceover] In this video, we're going to finish tidying up the clock, and we're going to take care of a few edge
cases. Scrolling down to my event calendar, everything looks pretty good,but my numbers are moving around a little
bit and also, I'm not showing whether this is 3:34 AM or PM. So, we're going to take care of those issues to start out
with. Switching back to my code, the numbers are moving around because my separator is actually changing from a
colon to a space, and in a font that's not fixed width.

That's going to cause a little bit of difference in spacing. So, I could change this to a fixed width font using CSS, but I'd like
to keep using the font that's there. So, what can we do? My recommendation is to use CSS to change the color of the
separator, instead of making it a different value. So, here's what we'll do. Instead of changing the separator, we'll set a
class and then change the class that's used on the separator. So, I'm going to change this variable to sepClass, and we'll
start out by leaving it blank.

And then, if the current number of seconds is odd, we'll change that class to something else.The CSS for this project
includes a class called trans that will set the color of an item to transparent, so let's use that. Now that that is set, we can
set our separator accordingly. So, this will be a colon and it will be surrounded by span tags that will change its color. So,
I'm going to concatenate all of these together. Here's my sepClass, and there we have it.

So, let's refresh the page and make sure this works. Very good, and no numbers are moving around. It's rock solid. Now,
let's add AM/PM support. This is going to be very similar to what we did with the hours up here. So, we'll add another
variable in the same spot. We'll call it ampm, and we'll set it initially to AM. And then if the hours are greater than
12, along with subtracting 12, we'll set ampm to PM, and then we can add this onto our time down here.

So, we have hours, our separator, the minutes, and now we can add on the AM/PM. Let's try that. I'll
refresh. 3:41PM. This might look a little nicer if we had another space in there, so let's add that. We can add them up
here. Or down here. Let's do it down here. Refresh one more time. There, looks great. Now, here's something else to
consider.

We've seen that many of the functions that the date object provides start counting at zero. This is going to impact us in a
couple of different ways. The first is, what happens at midnight? I'll just tell you that when it's midnight, the number of
hours will be zero, and we don't want to display a zero here in the clock. So, let's switch to the code and make a fix for
that. Right here where I'm dealing with the hours, I can deal with that case as well. So, first I'm checking if the hours are
greater than 12.

I'll add an else if, and now if the hours are equal to zero, I will set hours to 12. So that way, 12 will be displayed instead
of zero. Let's think of one more thing. Here we're using getMinutes,and this doesn't return a string, it just returns an
integer. So, if for example, it's 3:00, the number of minutes here is not 00, it's just zero.

And when it's 3:03, the number of minutes is three. So, what we need to do is pad this with an extra zero when the
number of minutes is less than 10. So, let's add that on as well. I'm going to add my minutes up here, right under
hours. So, we'll call this minutes, and we're using the getMinutes function. Add a little white space. And now down
below, I'll copy this, and say if minutes is less than 10, we're going to add a zero onto the beginning of minutes.

So, we'll say minutes equals zero plus the current value, and that will pad it. So, now that I have my padded minutes, I
just need to drop them in down here where I'm setting the time. Now, I'll switch back to the browser and refresh, and
there we go. We have a zero padded minute here. So, now we'll always be sure that our clock displays time the way a
clock should. So, that wraps it up. We fixed the formatting issues, and we fixed several edge cases. Our clock is in very
good shape.

Good job.

Challenge: Add the date

(electronic swoosh) - [Voiceover] For this challenge, we're going to enhance the Events calendar by showing the date, as
well as the time. It's much more useful when we're looking at events that have a date and a time to show both of
them over here in our Now box. I've hard-coded January 30th here. Let me right-click it and Inspect it to show you what
this looks like.Now as you can see, this is hard-coded right now in a current-date region. So this is what you're going to
be updating.

So we'll call this challenge,, Date and Time. You're going to add the date to that Now box, and format it like June 16, that
is the month, spelled out, and then the number of the date. This is relatively easy to describe, but it will take a few
minutes. Good luck.

Solution: Add the date

- [Voiceover] Let's take a look at one possible solution to the date and time challenge. Here we are. As I've mentioned, it
is currently June 16th, and June 16th does appear here in the Now box. Let's take a look at the code that I've used to get
there. So let's start at the top. First of all,I've renamed these variables to make them more clear. As I'm starting to add
more stuff just using C didn't seem all that helpful. So I've spelled it out to currentTime, and then I've added
currentDate, and I'm just using document.getElementById to retrieve that.

Then in the setInterval, I've stripped out the named Update Time function, because now we're updating the date and
the time, and just passed it in directly as an argument. The second argument of updating every thousand milliseconds is
still down here. So we're still grabbing a new date object every time. But now instead of only using hours and
minutes, I'm pulling in the month and the date. The date is easy enough. I'm just using getDate on the date object. That
pulls in a number, and a number is all I need.

It's never going to be zero or something weird. It's always going to be one to 31. Whatever's appropriate for the current
month. getMonth on the other hand is tricky. It's going to start at 0 and go up to 11. But I don't wanna display 0 through
11, I want to display the actual names. Now part of the reason that JavaScript represents these as numbers is because
depending on what country you live in and what language you're speaking, the names are going to change. So I've
written a helper function called formatMonth that will take that integer and reformat into the actual named month that
I want.

Let's scroll down and look at that. Here it is. So it takes as an argument that integer M, which I've done a little sanitizing
on. First I'm making absolutely sure that it's an integer using parseInt as we've seen previously, and then if I somehow go
crazy and decide to send in numbers that are less than 0 or greater than 11, I'm normalizing those. And then finally we
do the conversion of the integer into the month name. Here's one way you could do it. You could set up a variable for
the monthName, and then use a Switch statement capturing each case from 0, 1, all the way up to 11 and setting the
month name accordingly.

That would work just fine, but I didn't do it that way. Instead, I set up a variable that contains all of the month names of
interest. This is what we call an array literal. It's delimited by square braces and then I just have all the values inside
it separated by commas. Now arrays start with a 0 index, and then they go 1, 2, and so forth. And that's exactly the same
as what we get from dates getMonth method. So now all I need to do once I've set this up as long as all my months are
in the right order is return monthNames, that's this data structure, and use the M index that's passed in as this
function's argument.
So if M is zero I'll get back January, if M is one I'll get back February, and so forth. So that's done here. And then finally, I
changed this c.innerHTMl to currentTime.innerHTML to make it very clear what's going on, and then for
currentDate, because there's no HTML in here, just plain text, I'm using the textContent property we've seen
before. And it's just the month, a space, and then the date. And this is what you end up with.

So that's one possible solution. As with any of these challenges, there are lots of ways to do it.I just hope that the
process of getting to this solution was helpful to you.

Lesson5: Using the Google Maps API

What is an API?

- [Voiceover] Working on the website for H+ Sport. I have their address on their contact page,but it would be even nicer
to show a map. Of course, there's an easy way to do this. You can select the address, and copy it, and maybe go over to
Google Maps, and search for it. And of course, this is not the actual H+ Sport. That's a fictitious business. This actual
address is for the Capital Records Building. Well let's just pretend that's where this business is located. So we can share
it, click embed, and copy this to embed a map.

And if I open my html file, I can scroll down to the area where the location is, paste in the embed code, save the
file. Now if I go back and refresh, just like that, I have a map. That works fine, but I don't have a whole lot of control over
how this map looks or what happens when a user interacts with it. To get that kind of flexibility, I need to use the Google
Maps API, that is, a software toolkit provided through JavaScript, that lets me change maps.

All right, let's talk about what an API is, and how you would use one. So when I say API, I'm referring to an Application
Programming Interface. In this case, when I say "application," that's the page or the app that I'm working on. And the
API is the official way to use someone else's JavaScript, and use someone else's resources to create something on your
own site. I find that one of the biggest challenges when working with an API, other than the challenges of programming
in general, you know, just fixing bugs, and stopping yourself from making too many mistakes, is the terminology.

So you may know what you want, but you won't necessarily know what it's called, because an API is written by a
developer. So they might have to be very careful about how they name things to avoid collisions with other
terminology. So they won't necessarily use the same termsyou would, when you're trying to solve any given
problem. This is where example code and documentation is your friend. A well-written API usually includes good
documentation and useful example code that you'll be able to copy and paste to get yourself started.

Many services and websites offer JavaScript APIs. Google offers many many JavaScript APIs,including Maps, which we'll
be using in this course. Bing also offers a Maps API. YouTube offers APIs for controlling their players, as does
Vimeo. SoundCloud also offers an API, but in their case, they call their API an SDK, or a software development kit. So
when you're looking for an API or a way to interface with somebody else's service using JavaScript, you can search for
the service's name, and then JavaScript API, or JavaScript SDK, and see what comes back.

So that's what an API is, and going forward, we're going to see how the Google Maps API works to add a map to our
website that really works how we want it to.

Create a map

- [Voiceover] Over the course of the next several videos we're going to use the Google Maps API to create a fully
customizable map here on H+ Sport. So the first thing that we need to do is go to Google's developer site and start the
process of initializing their API. They have a variety of Maps APIs available. We're working on a website, so we'll choose
Web. And I want to mention, APIs change all the time. So the process you'll go through to get your API Key and follow
the instructions might be a little different than we're doing in this course.

But the general process of finding where the API is and then getting the keys and looking at the documentation should at
least be similar. So so here we have the Google Maps JavaScript API. This is the one we're definitely going to be
using. And they require a key. There's a button up here that says Get a Key, so we're going to do that. An API Key is used
to authenticate you as a user of their API. So if they make changes, theoretically they could notify you that something is
going to change and you might need to oupdate your code.

They could also do what's called Rate Limiting to make sure that you don't hit the API too many times if your website
gets really popular. And maybe at that point, you need to upgrade from a free version to a paid version. Fortunately
Google Maps is very generous with the free use and it shouldn't be a problem. So we'll click this Get a Key button and
now I have this modal dialog telling me the steps that I'm going to need to follow. Now it's asking me to either create a
new project or reference one that I've created previously. I'm just going to create a new project.

This will take a few seconds. Now I have the opportunity to name this key. So I'm going to call it My Maps Project. But, of
course, you can call this anything you want. And then I'm able to tell this key which websites it should be accessible
from. This is especially important because the API key will be visible in the source code of your page. So someone
theoretically could grab the key from your code and use it on a different website. If you were using a paid plan with your
API key, this could be especially damaging if some one else steals your API key and uses up a lot of your resources.

Now in this case, I don't need to limit it to anything, so I'm just going to leave this blank. But this is something to keep in
mind. Now I've created the key and here it is. So I'm going to copy this and bring it over into my source code. Now when
we're done with this course, I will delete this API key so you won't be able to use it if you follow the examples exactly as
they're written here. You're going to need to get your own API key by following the same process to work in your own
code. So over here in my script file, I'm just gonna make a variable, call it gMapAPIKey and save it here.

I don't know if I'm even going to use it here, but I just want to have a place to save it for now.Switching back to the
browser, I can say OK. And basically we're done with this part. I have my API key and now I can use the Google
Maps Javascript API. So now that I know that I can use it, how do I use it? They have a lot of documentation here: guides,
references, tutorials. Let's take a look at the guides first. And I can see right away there's a Hello World example
here.You won't always get this lucky, but hopefully you will.

So I'm going to scroll down here and copy some of these pieces and bring them into my code.So I can see that there's a
script tag that loads the Google Maps API for me. And once again, I'm called out that I need to use my own API key. This
applies to you just as much as it does to me. And then I have some actual Javascript here, and the DIV tag where the
map lives. Also note, there's a bit of CSS up here that might come into play. So first let's copy the script tag.Switching
back to my editor, I'm gonna scroll all the way down to the bottom of the page using Command + Down Arrow.

And here's my custom script file. So because Google placed their script tag after their defined script, I'm gonna paste
their script tag after mine. And then back here, I'll copy my API key and paste it in. Everything else is the same. So I'll
save that. Switch back here. And now I'll grab their actual Javascript, and paste that into my script.js file. And real quick, I
just want to mention the API key one more time.

It isn't actually used in this file, I just pasted it here for convenience. But anytime you see my key in the videos, you need
to swap it out for your own for the examples to work. I'll fix the indentation here, make it a little more readable for
myself. Now normally I'd insert all this Javascript inside an iffy, and immediately invoked function expression like
this. This would protect all of my variables and make sure I'm not overwriting anything. But because of the way that the
Google Maps API works, it wants your function to be in the global namespace.

So I'm leaving everything just as it is inside the script file without any wrappers. Okay, I can save that. And now switching
back to the HTML file, I know that I need to add that DIV tag. So let's scroll up to where the content appears. Here we
are. Here's my address. And now I need a a DIV to insert the map into. So I'll give it an ID. Let's call it hplus-map,
okay. Now I'll copy this.

Now I don't see anything in their script tag that needs to change. But in their Javascript, here it is. Here's the
getElementById that selects my map. So I need to use the ID that I've actaullyused in my markup. And save that. Save
the index.html file. And then switch back to the browser and try it out. I'll refresh, and I do not see a map. Let's inspect
this area and see what's going on. We'll look at the console for errors. These seem to be related to something else.

I don't see anything that says Google Maps API. So let's look at the elements. Here we go.Here's my hplus-map, it
definitely has a lot of stuff that I didn't insert. So it looks like the Google Maps API is actually working. But I probably
need to tell it how big the map should be. There was some CSS here. Okay, so let's do that. I'll scroll up to the HEAD tag
where the CSS is. I'm trying to find a good place to put this.

There we go, right at the hend of the HEAD tag. I'll just create a new style. And then hplus-map, we'll give that a known
size. We'll say it's 100% wide and then make it 400 pixels tall.That'll work. Switch back here and refresh. And there we
go. We have a map. Now of course it's showing Sydney Australia, not where we actually are. But we'll work this one step
at a timeand slowly build it up until it's exactly how we want it to be.

But at this point, you've seen how to get your API key for this particular API, and how to initialize it using their example
code.

Change the center point

- [Voiceover] In this video we're going to make our first customization to this map, which is kind of important. We're
gonna change the center point so it's located where we want the map to actually be located. Currently we're
somewhere on the coast of Australia. And we need to be in Los Angeles. So, let's look back at the code. It's pretty
readable. I'm initializing a new Google Maps object. And then, there's a second argument, which has these keys, center
and zoom.Center looks pretty obvious like what I want to change.. And this object is latitude and longitude.

That's pretty clear. Now, unfortunately, I don't know off the top of my h ead of my head, what the latitude and
longitude of the address of interest is. But I can find out pretty easily. Looking at the Google Maps API reference page, I
can see when I load this, that it loads up an Experimental Version. Let's go with the Release Version, just to be safe. In
this API, I know thatthere's something called a Geocoder. A Geocoder is what can convert an address to latitude and
longitude and vice versa.
So, I could instantiate the Geocoder class and do that in my Javascript code. But for our purposes, we just want to set
one point and just get that one point's latitude and longitude. So doing this with the API is a little bit overkill. We just
need to find out the answer once. So let's use a Geocoder web service to find that out. Here's one at
GPSVisualizer.com. So what I need to do here, is plug in the address, say which source I want to pull the latitude and
longitude from, it doesn't necessarily matter which one.

And then, Geocode it. Alright, let's copy the address, past it into our Geocoder, then Geocode it. Here's my answer,
latitude and longitude. So I can copy these numbers and switch back to my text editor and paste them in. We can save
that and switch back to the browser. Now I'll refresh the page. There we go. We're centered very clearly on Los Angeles.

Now, looking at this, you can't actually see where we are, it's a little bit too high zoom level. So our next step will be to
change the zoom level and some other options.

Change the type and zoom level

- [Voiceover] In this video, we're going to look more deeply at setting some options. And indeed, we're going to use
some of the methods that Google Maps makes available to us to make setting some of those options easier. So, scrolling
down to my map, everything looks fine, except I'm way too high above Las Angeles. We wanna see where we really
are. Also, there are some different types of maps available. Not just map and satellite. We're gonna try some of
those. So, we'll start with the map types.

Over here in the Google Maps API reference, if I just search the page for "type". Here we go, map type. So along with
just doing an in-browser search, I can click these different classes to get some more information about them. That's
pretty handy. So I can see that these different map types are available. Now, if I want to use one, I need to figure out
how to specify it in my map options. So let's remember that we have hybrid, road map, satellite, and so forth.

I can see over here, in the sidebar, that there's a map options object. This looks promising. So let me look through
here. Here we go, map type control. Map type ID. That looks like what we want. So, I can see that the default is road
map, and that the key is map type ID. So lets look at those different types again by clicking that link. Let's try the hybrid
one. I'll copy this, switch back to my browser, and then change the map type ID to hybrid.

I'll save that and switch back to my browser. I refresh, and I can see that this, apparently,doesn't work anymore. Wonder
what happened. Let's look at the Javascript console. Okay, so I can see that hybrid is not defined. I think I know what
happened, here. These are constants within the Google.maps.MapTypeId class, and I just used the constant by its own
name. So Javascript thinks that it's just a variable. I need to tell it where to find this.

So, let's switch back to the code again. And spell the whole thing out. I'll save that again and switch back. Much
better. So, in this hybrid map, we have the satellite terrain, and then the road map overlaid on top. We also have the
terrain map, and then just a satellite map. These are actually available through the controls, here. Here's the terrain
map. So I can set these as constants, if I want to.

I think for our purposes, the default type of road map is a good choice. Even though it's the current default, we can set it
here to make sure that that's always used, even if the default changes. Alright, now lets take a look at the zoom. Let's go
back and refresh this. Now what would be ideal is to figure out, visually, where I want this map to be zoomed, and then
have the map tell me what zoom level it's actually at. So, referring back to the reference, let's search for "zoom".

Okay, it's used a lot here. So what we really wanna do is try and get the value. So a lot of times in most APIs, you'll have
get methods. They're often called "getters". So, let's see if there's something called "getZoom", for example. Ah-
ha. There it is. And this is defined in the Google Maps map class. So we can see there's a whole bunch of methods that
are available here that can tell me information about the map as it currently is. Great. So here's what we'll do. Let's open
up the Javascript console.

Hide some of these warnings and messages. And now, referring back to my code, I can see that the variable is called,
"map". So if I type that into the console, I can see, once I type a dot,that I have various methods available, including
getZoom. Let's run that. So the map is currently set to a zoom level of eight. Let's drag this over. Zoom in a little bit.

In fact, I'm gonna refresh this so we make sure we're centered in the right place as we're playing with this zoom. Clear
the console again, and we'll start zooming in. Right about there looks good. So let's try that map.getZoom again and see
what we have. 12. That's great. So, I've been able to use the controls in the map to get it set exactly how I want it to be
set, and then I can use the methods that are available to tell me more about it.

So, I know that I wanted to try a zoom level of 12. Of course, there are many other methods available, as well. I could set
the center this way by using getCenter. And if I do this, I get a value back that's named kinda strangely. Okay, I can see
that I have a latitude and a longitude,but it's a function, not a value. If I dig far enough, eventually I find some
numbers. But when I see something like this, that indicates that I'm probably not doing it correctly.

Let's go back to the reference, and see what we get here. Let's look at the documentation for getCenter. So I can see
that it returns a LatLng class. So, if I click that, I'm sent to the reference for it. And then I have some methods, here. Now,
this looks more promising. I can call Lat and Lng on that return value to get the latitude and longitude. I also have a
toString method, which could show it to me as a string. Let's try that.

So, I'll switch back to my tab with the map. And I'll call getCenter. And I know that this returnsthat latitude and longitude
object. So I should be able to just call Lat right on that. There we go.And I get back that same value. I'll just compare this
to my code to make sure it looks pretty much the same. And it does. We also have that toString method that gives me
the whole thing as one string. So once again, I'm very pleased with how I can interact with the map by messing around
with it, and then seeing how the value changes.

Okay, let's set another couple of options. The intention of this map is to show people where we're located. So once we
have the center point set, we don't really need to be able to drag this around anymore. So let's see if there's a way that
we can stop this from being draggable.I'm gonna go back up to the map options. And here we are, draggable. If false, it
prevents the map from being dragged. Dragging is enabled by default. Very good. So, let's set that to false.Draggable is
false.

Okay. Go back and refresh this. And now, I can't move the map with my mouse. And let me just scroll up, oh,
whoops. Ah-ha! So, when I scroll, I can't drag this now. Scrolling changes the zoom level. And I wanted to lock that in as
well. So let's find out what the option is for that. It'll probably be under scroll. Here we go, scrollwheel. This is also a
boolean, and it is enabled by default. So we can set that to false, as well.

So this will be "scrollwheel", set to false. Now refresh this. Now I can't drag it. And scrolling takes me up and down the
page the way I'd hope. Very good. One last change. These options are all set as keys in an object. And I like to change
these to strings, to make it a little more explicit what they are. You can also do some nice formatting to line them up. If
you like. I usually just keep one space in between the name and the value.

There you go. I'm pretty happy with this. So, we have our map centered where we want it to be, and we've disabled
some of the features that could cause someone to accidentally relocate the map somewhere that we don't need to
see. So that's a look at how to set some of the options on the Google Maps API, and how to navigate the reference for
an API, in general,to find the things that you're looking for.

Add a marker

- [Voiceover] At this point my map is looking pretty solid. It's centered in the right place. I can't do anything to it that
would put it in the wrong location, but I don't have one of those little pointer doodads showing exactly where we are on
this map. So we're going to create one of those. Now of course, pointer doodad is probably not what they're gonna call
it in the API. So let's take a look at some code samples to see what it is that we're looking for. Here in the Code Samples
area I can scroll down the left side to look at what we have.

Signed In Maps, Events, Controls. Controls might be it, but I don't see anything that looks very promising there. Styles,
Drawing on the Map, oh, here we go, Simple Markers, that sounds about right. Yes, indeed that is what I'm looking
for. So how do we create one of these? I'll scroll down and look at their sample code. Aha, here we go, all I need to do is
create a new marker and just tell it where it needs to be located. This looks pretty similar, I just need to copythese lines
above the marker, so let's do that.

Switch over to my code, we'll add this onto the end. So I create this marker with a few options, I have the position which
is currently set to a variable that I haven't defined yet. I set the map where it needs to be displayed, and then the title,
which presumably is going to be shown on the marker somehow. First let's deal with the location. Looking back at the
sample code, I can see that this is defined using an object with the latitude and longitude, so I'll copy that and switch
back, and this is very much like what my center is.

In fact, it's exactly what I want. So now I'm gonna use that location twice. So I will save this in a variable and I'll call it
storeLocation, only instead of using their sample location, I'm gonna use mine. And then I'll drop this in as the center
point, and then as the position where my marker is going to be. Map is the same, and just to avoid confusion here, I'm
going to make sure that these keys are strings. This just helps me avoid confusion with which is which here.

This is the key, this is the value, which is defined up here, and then finally the title, which is currently Hello World, but
why don't we make it something that's actually meaningful to us.hplus sport in Los Angeles (actually Capitol Records in
real life) Okay, let's save that and switch back to the browser. Here we go. I have my marker, and when I mouse over
it, nothing seems to happen, let's try that again.

There we go, so I get a tool tip from the browser using what's probably set as a title attribute.This works fine, but what
would be even better is to have one of those pop-up boxes when you click the little marker, and we'll look at how to do
that next.

Add a popup to the marker


- [Voiceover] In this video we're gonna take the next step with the Google map, which is to add a pop-up window to this
market. So right now when I click it, nothing happens. I have to sort of carefully hover my mouse over it to get my little
tool tip. But I'd like to see that pop-up window that shows a little bit more information here in the context of the map
when I click on that marker. So let's see if we can figure out what that thing is called. I'll try searching the whole page for
pop, and nothing comes up, so obviously pop-up is not the right terminology.

Let's look back where the markers are defined and see if there's anything similar in the same section. Simple markers,
labels, wonder if that's it. Looks like that changes what's actually on the marker itself. We'll look through some of these
others. What's an info window? Ah, there we go, that's just the ticket. So let's see how you create an info
window. Scrolling down here to the code example, everything up here looks pretty similar to what I have so far, but then
I have this giant content string, and then down here I have a variable called InfoWindow, so obviously this is what we're
gonna need.

So it looks like what we're doing is we're creating a variable which is instantiating this Google Maps InfoWindow
class, and then we're passing into it an object with one key, content, whose value is this content string. And then here's
the marker, and then finally, there's a marker.add.listener, so this is an event listener using the custom Google Maps
event listener library to add a click-handler which then opens the info window. All right, that all makes sense.

Let's copy this example. Over here into my script, I'll change the indentation. So we need to define the content string. I'll
create another variable up here called popupContent. Let's say H+ Sport, and maybe we'll add another couple of lines
here. So we'll use string concatenation using += and we'll add on the address, 1750 Vine St, do the same thing again, Los
Angeles, California.

We're gonna need some break tags in here, there we go. So popupContent will be the variable I'll use down here. Okay,
let's see if there's anything else in this example that I need.Ah, yes, the event listener. So the marker is defined, and then
we need to pop open this info window. Once again, fix the indentation, and then we'll call infowindow.open with
marker, the variables names match here, and map, those match as well.

So basing my code on the example code means that I don't have to change very much to get exactly what I want. So let's
save this and switch back. I'll Refresh, scroll down and give this a try. There we go, looks good. Now I can see there's a
little more example code for perhaps one of these giant popup boxes where I can set a maximum width on the info
window. That could be useful in other circumstances, as you can see here, but for our purposes, that simple code is
enough, very good.

So that's how you can create what is apparently called an info window on a marker in your Google Map.

Challenge: Modify the map

- [Voiceover] Business is going really well for H One Sport. So much so that they've opened another location. I've added
some information on that new location to this HTML file. You could see it's here at 1000 Vin Scully Lane. In reality this is
Dodger Stadium. So what we need to do is update this map to account for that new location. Here are the parameters of
the challenge.We're going to add another location. The address is 1000 Vin Scully Avenue in Los Angeles.This is really
Dodger Stadium as I mentioned.

So what we need to do is add a marker and an info window for that new location and then recenter and zoom the
map so that you can see both of the locations, that is both the markers for those locations at the same time
comfortable. That's your challenge. It should take maybe 10 minutes or so. If it takes longer than that, come back and
we'll go over it together.

Solution: Modify the map

*light ding* - [Voiceover] Let's take a look at one solution to this new location challenge. Scroll down to the map and
here is the original Hollywood location, which I've renamed H+ Sport Hollywood. And then H+ Sport in Chavez
Ravine, which is the location of Dodgers Stadium. So the map has been re-centered so we can see them both
nicely. Each has its own popup.

And that pretty much takes care of it. So let's see the code. Basically what I've done, is duplicated almost everything that
I did with the original and just renamed some variables. So up here, I have the store location for the Hollywood
location. And the one for the new location in Chavez Ravine. So first I found the Chavez Ravine location by
geocoding, which we'll look at in a second. And then for the center point, I moved the map around until I had both the
points centered and then I used the get center method we looked at previously to get the new location.

That center point is passed in as the center of the map. And then down here, I have my popups. So here's the original
one just renamed to popupContentHollywood and then the same thing for Chavez Ravine. Likewise, we have an
infowindow for the Hollywood location and the Chavez Ravine location. The markers, with new titles. And then the click
event listeners for both of them. When you start writing code like this, where you have similarly named variables, using
similar kinds of data, you're starting to approach a point where refactoring your code in a more object oriented fashion
could make sense.

It's a little bit beyond the scope of our discussion here, but that's an area that you can look intoif you've solved the
problem like this. This code is pretty readable, so I kept it this way for this example. So that completes what we needed
to make this challenge work but I want to show you one little bonus. I added a function called geocodeAddress, which
meant that while I was working on the map, if I open my JavaScript console, I'll clear out these messages. Now I have a
function called geocodeAddress into which I can pass an address and get back its latitude and longitude.

So I did this for 1000 Vin Scully Ave, Los Angeles, CA. And then I get the latitude and longitude back. This meant that I
didn't have to visit an external web service. Where did this come from?Well, I went back to the Google Maps
reference and here, in the sidebar, I searched for geocode and came up with geocoding service they've offered. Now, I
can paste in the address here as well. And geocode it.

But I don't see the latitude and longitude, it just re-centers the map on that point. That's all well and good, but I wanted
to modify it a little bit so I could get back that answer and use it and use it in the console. So I took their sample code,
here, and made some modifications so that it would return the value to the console instead. Here's what that looks
like. So it's just a function in the global name space that takes an address as its argument. And then I initialize a new
geocoder, which comes straight out of their example code, and then I call the geocode method built into that geocoder.

For its first argument, I'm passing in an object and telling it that I'm passing in an address, that is, not a latitude and
longitude. And the way this is written, there's a callback functionafterwards, which is fired after the results are
retrieved. And that function takes two arguments, results and status. The status can be checked against the geocoder
status class and so there's a constant in there that says, okay, in other words, this worked. And if it worked, I'm logging
to the console the results, which come from that results argument, which is in a ray, so I'm pulling off the first
result using the zero index and that has properties of geometry, followed by location, and then I'm calling the toString
method on that.

Referring back to the example code, you can see here's the results, geometry, location. And so all I needed to do was call
that toString method we've seen before to get the address into the console where I could copy it and paste it. So there
you go. That's a solution to this challenge. There are, of course, lots of way you could have solved this challenge. I hope
you found the process of getting to the solution enjoyable.

You might also like