IntroductionWelcome| 00:04 | Hi! This is Simon Allardice,
and welcome to JavaScript Essential Training.
| | 00:08 | JavaScript is the programming language
of the web invented for the web to add
| | 00:13 | behavior and interactivity to your pages.
| | 00:15 | We'll begin with the basics: the core
of JavaScript language and syntax, how to
| | 00:20 | write it, where to put it,
what tools you can use.
| | 00:24 | We'll then start to go step by step through
the different things you do with JavaScript.
| | 00:28 | We'll work with forms, work with events,
get to really understand the DOM, the
| | 00:34 | Document Object Model, the way you
will understand and change your pages in
| | 00:38 | reaction to what the user is doing.
| | 00:40 | You'll see how to debug JavaScript.
| | 00:43 | We'll also explore the popular
JavaScript libraries like jQuery, and we'll wrap
| | 00:47 | up with some more advanced topics.
| | 00:49 | And along the way, we'll see a lot of best
practices that have developed over recent years.
| | 00:54 | So whether you're brand-new to
JavaScript or perhaps you've been working with it
| | 00:57 | on and off for years, welcome
to JavaScript Essential Training.
| | Collapse this transcript |
| What you should know| 00:00 | In this course, I'm starting with the
idea that you know some HTML and you know
| | 00:04 | some CSS, because JavaScript is a
language that works with and manipulates
| | 00:09 | web pages, so I expect you
know how to make web pages.
| | 00:13 | And that even if you use a WYSIWYG
design program like Dreamweaver, you could,
| | 00:17 | if you had to, still open up a text
editor and write a basic HTML file with
| | 00:22 | correctly nested elements.
| | 00:24 | You don't have to be a guru.
| | 00:25 | I don't expect you to write a
transitional XHTML doctype tag from memory, but
| | 00:30 | you could make a simple page that works.
| | 00:33 | And that similarly, with CSS, you're
good with creating and applying styles to
| | 00:37 | elements, working with IDs and classes.
| | 00:40 | And if that's not the case, take a look
at our other courses at lynda.com first.
| | 00:44 | Now, I don't expect you to be a programmer.
| | 00:47 | We are going to start from scratch.
| | 00:49 | Though if you know about
programming fundamentals, variables, loops,
| | 00:52 | conditions, that's very useful.
| | 00:54 | And of course, if you are an
experienced programmer, that's great and welcome.
| | 00:58 | Be aware that in the next few movies,
we're going to cover the core language
| | 01:02 | syntax of JavaScript,
much of which is based on C.
| | 01:05 | So, if you've spent several years
living in C or C# or Java, yes, you're going
| | 01:10 | to see some things that you
already know, so expect that.
| | 01:13 | JavaScript did not try and invent
a new way to write an if statement.
| | 01:17 | So, you might be tempted to jump ahead,
but I do suggest you go through all the content.
| | 01:22 | Now, I just invite you to relax and
enjoy the ride early on, because even in the
| | 01:26 | initial stages, you're going to see
things that are different from what you
| | 01:29 | expect, even in the most fundamental content,
like creating variables and checking equality.
| | 01:35 | And it's those little differences that
the existing programmers need to focus
| | 01:39 | on, the basic things you take for
granted but just don't apply in JavaScript.
| | Collapse this transcript |
| Using the exercise files| 00:00 | If you're a Premium member of lynda.com,
or if you're watching this tutorial on
| | 00:04 | a DVD-ROM, you have access to some
exercise files used in this title.
| | 00:09 | I have the folder here downloaded to my Desktop.
| | 00:12 | It's just a folder called Exercise Files,
and in that, you'll find each of the
| | 00:16 | relevant chapters will have its own folder.
| | 00:19 | And in some of these folders, there are
files that represent some simple assets
| | 00:23 | that I'll be working with during the movies.
| | 00:25 | And we'll point those files out at the
relevant time by just showing you the
| | 00:29 | path to the file location.
| | 00:30 | These are all just for convenience.
| | 00:32 | They're not required, but they
do make things a little easier.
| | 00:35 | Now if you don't have access to the
exercise files, you can follow along from
| | 00:39 | scratch or just create your own assets.
| | Collapse this transcript |
|
|
1. Getting StartedIntroduction to JavaScript| 00:00 | So before we start writing some JavaScript,
let's get some core concepts cleared up.
| | 00:05 | It's very common to see JavaScript
referred to as one of the three core
| | 00:09 | languages of web pages.
| | 00:11 | You have the HTML markup
language for content and structure.
| | 00:15 | What's your headline, how many
divisions are in your page, how many paragraphs
| | 00:19 | do you have, what are the
contents of those paragraphs?
| | 00:22 | Then the CSS, the
style sheet language, for presentation.
| | 00:25 | What font does the headline use, what's
the background color of the page, what's
| | 00:29 | the width of the div that the paragraphs are in?
| | 00:31 | And JavaScript, the programming
language for your behavior and interactivity.
| | 00:37 | What happens when you mouse over a
menu, what happens when you type the
| | 00:41 | wrong value in a form field, how
long does a photo slideshow take to move
| | 00:45 | from one image to the next?
| | 00:48 | JavaScript is a programming language
that you'll often hear it referred to as a
| | 00:52 | scripting language, and sometimes
you'll hear some software developers dismiss
| | 00:56 | JavaScript as just being a scripting language.
| | 00:59 | And what they mean by that is that
JavaScript is intentionally limited.
| | 01:03 | I can't write a desktop application in
JavaScript the way I might do with C++ or
| | 01:08 | Java or .NET or Objective-C.
| | 01:12 | JavaScript only works inside
another application, the web browser.
| | 01:17 | Whether that's IE or Safari or
Firefox or Chrome or Opera, they all have a
| | 01:22 | JavaScript engine inside them.
| | 01:25 | The operating system runs the web
browser, the web browser contains a page, and
| | 01:29 | the page contains the JavaScript.
| | 01:32 | Now another way JavaScript is limited is
that yes, it doesn't have access to the
| | 01:36 | file system of the
computer that it's running on.
| | 01:39 | There are no words in JavaScript to
open or save local files because that
| | 01:43 | would be a security risk.
| | 01:45 | There are no words in JavaScript to
talk to a database or target a USB port.
| | 01:50 | And that strikes some software
developers as odd because most languages are all
| | 01:55 | about input and output, and JavaScript isn't.
| | 01:58 | But of course, they're missing the
point. JavaScript wasn't designed as a
| | 02:01 | general purpose programming language;
| | 02:03 | it was designed to manipulate
web pages and it does that very well.
| | 02:07 | Now as you know, when a user opens
their browser and requests a page from your
| | 02:13 | web site, they're just send HTML and CSS
as plain text, and you let their browser
| | 02:19 | take care of interpreting and rendering it
| | 02:22 | however their browser wants to,
whether it's mobile, whether it's on a laptop
| | 02:26 | or a desktop, and it's the same with JavaScript.
| | 02:29 | JavaScript is a client-side language.
| | 02:33 | It is sent to the user's
computer and it runs there.
| | 02:36 | That's as opposed to server-side
technologies like PHP, ASP.NET, Ruby on Rails.
| | 02:42 | They'll execute their code on the web
server and deliver the results to the client.
| | 02:46 | But with JavaScript, we just send our
code to the client and we let them run it.
| | 02:51 | I'm going to just interject a side note here.
| | 02:54 | JavaScript was designed to run as a scripting
language using a web browser as a host program.
| | 03:00 | That's why it was invented.
| | 03:02 | But because it has become so popular,
it has in recent years popped up as a
| | 03:06 | scripting language in other
applications, and even in server-side products.
| | 03:10 | So you'll find it in things
like Adobe Acrobat and Photoshop.
| | 03:14 | JavaScript is in server-side products
like Node.js and Google Apps Script.
| | 03:19 | But in this course, I'm not
focusing on those uses of JavaScript.
| | 03:23 | I'm talking about classic JavaScript,
a client-side language used to add
| | 03:28 | interactivity to web pages.
| | 03:30 | Now if you're interested in JavaScript
for any other reason, use this course
| | 03:33 | to learn the core of the language, and then
you can jump into those other applications.
| | 03:38 | So back to talking about
JavaScript as a client-side language.
| | 03:42 | One impact of this is that because
JavaScript is sent to the client, to the
| | 03:46 | user, is what if the user has
disabled JavaScript in their browser?
| | 03:51 | Well, then we can send it
over, but it won't do anything.
| | 03:53 | It will be as if the JavaScript never existed.
| | 03:57 | Now while this situation is less common
these days than it used to be, that does
| | 04:01 | mean we need to do our best to write
web sites that will work whether or not
| | 04:05 | JavaScript is enabled.
| | 04:06 | But yes, we want to add all of this
cool functionality, but if the user doesn't
| | 04:10 | have JavaScript, the web site still works.
| | 04:13 | It might have more limited
interactivity, but it's still perfectly usable.
| | 04:18 | Now another issue can be the
variety of browsers out there.
| | 04:21 | Just has different browsers can render
and display web pages differently, usually
| | 04:25 | because they don't handle CSS exactly
the same way, what happens if they handle
| | 04:30 | JavaScript differently?
| | 04:31 | Well, this was one of the reasons why
JavaScript had a bad reputation for a long time.
| | 04:37 | Go back a few years and a lot of
JavaScript had to be written to detect the
| | 04:41 | browser and handle different
browsers in different ways.
| | 04:44 | And I'm very happy to tell you
that's not really an issue anymore.
| | 04:48 | There are a few edge cases, but typically
we don't care what browser the user has.
| | 04:53 | And to understand why, let's do a
super-quick history lesson here.
| | 04:57 | So JavaScript was developed in 1995 by
Brendan Eich at Netscape, and it first
| | 05:02 | became built into a web browser with Netscape 2.
| | 05:05 | It was originally going
to be called LiveScript.
| | 05:08 | But because Sun's Java language was the
new big deal at the time, Netscape and
| | 05:12 | Sun had an agreement to rename
LiveScript to JavaScript to jump on that
| | 05:17 | popularity bandwagon of Java.
| | 05:18 | And most people these days agree this was
a bad idea and caused a lot of confusion.
| | 05:24 | The two languages have
nothing to do with each other.
| | 05:26 | If you're brand-new to programming, they
might look a little similar to you, but
| | 05:30 | that's because they both really look like C.
| | 05:32 | So JavaScript is not Java.
| | 05:35 | It is not a light version of Java.
| | 05:37 | It was not based on Java.
| | 05:39 | It doesn't matter if you know Java,
and we will talk no more on the matter.
| | 05:43 | Now as it became popular in Netscape,
Microsoft then made their own version
| | 05:47 | for Internet Explorer.
| | 05:49 | They couldn't call it JavaScript, so
they called it JScript, and we had more
| | 05:52 | browser differences to deal with.
| | 05:54 | And what happened, thankfully, then was
that Netscape submitted the language to
| | 05:58 | the ECMA or ECMA standards body to
create an independent and officially
| | 06:03 | standardized edition, and they did.
| | 06:06 | The standardized edition of this
language is officially called ECMAScript, and
| | 06:10 | it was first published in '97.
| | 06:12 | And really what we're doing in this
course is ECMAScript. That's a name by a
| | 06:17 | committee, so everyone just called it
JavaScript, even though Mozilla officially
| | 06:21 | owned the JavaScript name.
| | 06:22 | Now ECMAScript has had a few different
editions, but the one we care about is
| | 06:28 | edition 3, which may surprise you.
| | 06:30 | It was published way back in 1999,
but that's the one that you can reliably
| | 06:35 | assume full support for in every major browser,
| | 06:40 | and it's the one we're going
to focus on in this course.
| | 06:43 | ECMAScript Version 5 was published at
the end of 2009 and adds a few features to
| | 06:50 | the language, particularly in the advanced area.
| | 06:52 | But I'm recording this course in
mid-2011. ECMAScript 5 is only now
| | 06:57 | getting some support in the
most recent browser versions.
| | 07:00 | Adoptions of standards like this take
years, and yes, at some point in the
| | 07:05 | future ECMAScript 5 will be
the standard, but it isn't yet.
| | 07:09 | And just to let you know,
compatibility was a big deal in development of
| | 07:13 | ECMAScript 5, so everything we do in
this course will be compatible moving
| | 07:17 | forward and it will also work in all
the older browsers for many years to come.
| | 07:21 | Now if you're wondering what happened to
ECMAScript 4 in those ten years between
| | 07:25 | edition 3 and edition 5, well it just
got way out of hand and they abandoned it;
| | 07:30 | ECMAScript 4 never happened.
| | 07:31 | Now, one of the benefits of having a
standardized language like this is it
| | 07:36 | doesn't matter if you're a Mac, PC, or
Linux person, it doesn't matter if your
| | 07:41 | server is Windows or Apache, if
your backend is PHP or Ruby on Rails or
| | 07:45 | ASP.NET or ColdFusion or none of the above;
JavaScript is completely agnostic on these matters.
| | 07:52 | There's no special tools required.
| | 07:54 | There's no licensing needed.
| | 07:56 | Sure, as with editing HTML and CSS, some
applications may make our life a little
| | 08:01 | easier, but all we really
need is a basic text editor.
| | Collapse this transcript |
| Creating your first JavaScript| 00:00 | So let's get started with
writing some JavaScript.
| | 00:03 | Well, JavaScript runs in a web page.
| | 00:05 | That is the container that it needs to sit in.
| | 00:07 | So step one, have a web page.
| | 00:09 | I have a very simple HTML
file here on my Desktop.
| | 00:13 | It's about as basic as they come.
| | 00:15 | I can open it up in a browser
here and take a look that it's
| | 00:18 | really straightforward.
| | 00:19 | I'm now going to open it up in a text editor,
and I'm just going to use TextEdit here;
| | 00:24 | the equivalent would be Notepad on a
PC, but you can use anything you like.
| | 00:28 | I'll just increase the text size
to make that a bit more readable.
| | 00:33 | And as you can see, it's super basic.
| | 00:35 | The HTML is just describing the
content and structure of a simple page.
| | 00:39 | We have a headline.
We have a couple of paragraphs.
| | 00:43 | We have an unordered list.
| | 00:44 | I don't even have CSS on this page.
| | 00:47 | I'm not worried whether this is
HTML Strict or XHTML Transitional;
| | 00:51 | we're just proving a point.
| | 00:53 | Well, just as we use opening and
closing h1 tags to surround a headline, or
| | 00:58 | opening and closing p tags to
surround a paragraph, I can use opening and
| | 01:02 | closing script tags to surround some JavaScript.
| | 01:05 | And we'll talk more about where we
should put these script tags in a little bit.
| | 01:09 | I'm just going to put them after
the closing tag for my unordered list.
| | 01:13 | So I'll do the opening tag, and then
I'll do the closing tag, and inside them
| | 01:18 | the script I'm going to add is
simply the classic first program in any
| | 01:22 | programming language: the word 'alert'
written in lowercase, open parentheses,
| | 01:28 | double quote, the phrase
"Hello, world!," closing double quote, close
| | 01:32 | parentheses, semicolon.
| | 01:34 | This is one JavaScript
instruction, one JavaScript statement.
| | 01:39 | Now to run it, I simply save this file,
and then I'll double-click it to open it
| | 01:48 | up in the web browser.
| | 01:50 | And this is all it does:
| | 01:53 | it pops up the annoying JavaScript alert box.
| | 01:55 | Now other browsers might render this
slightly differently, but the effect is the same.
| | 02:00 | Yes, this is boring; yes, this is simple;
and yes, the alert box is one of the
| | 02:05 | more annoying things that
JavaScript does; but this is where we begin.
| | 02:10 | Now we need to see how to add some more.
| | Collapse this transcript |
| Getting to know the tools and applications| 00:00 | Some programming languages are
tied closely to certain development
| | 00:04 | environments and platforms.
| | 00:05 | If you tell me you're writing iPhone apps,
I'm going to assume you're using Objective-C,
| | 00:10 | on a Mac, using Xcode.
| | 00:13 | If you're writing.NET apps, you're
probably using Visual Studio on a PC.
| | 00:18 | JavaScript has no such association.
| | 00:20 | There is no one true
program here, or one true platform.
| | 00:24 | It's as agnostic as they come.
| | 00:26 | So when I'm asked what application
I'd recommend for writing and editing
| | 00:30 | JavaScript, my answer is
"Whatever you're using already."
| | 00:34 | If you use Dreamweaver to make your
web pages, stay there to write your
| | 00:37 | JavaScript, or Coda, TextMate, BBEdit,
Visual Studio, Eclipse, Komodo, Emacs,
| | 00:43 | Vi, or whatever, if you know
your way around it, stay there.
| | 00:47 | Every modern web-development or
programming application supports
| | 00:50 | JavaScript editing.
| | 00:52 | Now for some of this course, I'm going to
use Aptana Studio available from aptana.com.
| | 00:58 | And I'm using this here for two main reasons:
| | 01:00 | one, it's free; and two, it's
available on Mac, PC, and Linux.
| | 01:06 | I'm going to record this course
mainly on a Mac, but that was a
| | 01:09 | coin-toss decision.
| | 01:10 | Whatever you're using is fine;
the platform is irrelevant.
| | 01:14 | Now this course does not require
Aptana, and I won't be spending time
| | 01:18 | exploring its features.
| | 01:20 | I'm just using it here as a simple
JavaScript and HTML code editor because it
| | 01:25 | would be tedious for me to use
TextEdit or Notepad all the time.
| | 01:29 | I want at least line numbers and
basic indenting and formatting.
| | 01:33 | So if you need an editor, check out
Aptana; otherwise, feel free to stay with
| | 01:36 | what you already know.
| | 01:37 | Now the second set of tools are more
important than your operating system, and
| | 01:42 | more important than even your
editing environment: the browser.
| | 01:46 | This is where your code runs.
| | 01:49 | Now you may have a favorite browser--
most people do--but there's really no
| | 01:53 | excuse for not having all the major browsers.
| | 01:55 | And I would suggest having
the latest version of them.
| | 01:58 | While you can make a case for
developing using older browsers to check
| | 02:02 | performance and backwards compatibility,
the benefit of the latest browsers is
| | 02:07 | that the JavaScript tools get a lot better.
| | 02:10 | And that's more important to us.
| | 02:12 | Now Internet Explorer in all its
versions still has the biggest percentage
| | 02:16 | of total browser market share,
but Firefox is the most popular
| | 02:20 | cross-platform browser.
| | 02:22 | It has great JavaScript debugging tools,
and it's what I'll be using most of the
| | 02:26 | time in this course.
| | 02:28 | So if you don't have it already, grab
yourself the latest stable version of Firefox.
| | 02:33 | I'm using Firefox 4 right now,
which is the current stable release as I was
| | 02:37 | recording this course.
| | 02:38 | And you should also go and install--
if you haven't already--the Firebug
| | 02:44 | extension, which you can get from getfirebug.com.
| | 02:47 | Now, this is a fantastic tool for just
general web development, but one of the
| | 02:52 | things Firebug allows us to do is
experiment with JavaScript directly in the
| | 02:56 | browser without even creating HTML files.
| | 03:00 | So I'm going to jump over and install this,
find the latest version, which for me is 1.7.
| | 03:09 | This has point releases quite often,
so you're likely to see a different version of it.
| | 03:14 | I'm going to go ahead and select to install it.
| | 03:17 | And once the browser restarts, I have
Firebug installed. And I can actually turn
| | 03:22 | it on and off by clicking down here.
There's a little bug icon at the lower
| | 03:26 | right-hand side of the status bar.
| | 03:28 | And I can just use it to
toggle the Firebug panel on and off.
| | 03:31 | It can also be set to open up in its own
window, but I'm going to leave it here for now.
| | 03:36 | One of the great things Firebug allows
us to do is experiment with JavaScript
| | 03:40 | directly in the browser
without even creating HTML files.
| | 03:44 | I'll get deeper into Firebug later on
because it has several useful sections
| | 03:49 | that I can get to by clicking the
links on the panel here, but the one I'm
| | 03:53 | interested in is the Console one.
| | 03:55 | Right now, it's giving me a message
that the Console panel is disabled, so I'm
| | 03:58 | going to click the little dropdown
arrow here and say I want to enable it.
| | 04:03 | And it pops up a couple of messages
here that it's enabling the JavaScript
| | 04:06 | debugger to support Console and so on.
| | 04:08 | You see right down here at the bottom
where I've got the three Greater Than
| | 04:12 | signs, I can actually just
directly type in JavaScript and run it.
| | 04:15 | Just write a statement and hit
Return or Enter to execute it,
| | 04:21 | in this case, popping up an alert box.
| | 04:24 | However, one line at a time is a
little tedious, but over here again at the
| | 04:28 | right-hand side, I have this little
button called Command Editor, and if I click
| | 04:32 | that, what it's going to do is
divide this panel into two pieces.
| | 04:36 | I can just drag it to resize, and I
actually type in as much JavaScript as I
| | 04:40 | want over here on this side.
| | 04:46 | I could type several lines.
| | 04:47 | When I'm done, I come down and click the Run
button at the bottom and we pop up that message.
| | 04:53 | On the left-hand side, we'll see kind
of a mirror of anything that we've typed
| | 04:57 | and any diagnostic messages
that it may have given us.
| | 05:00 | We'll make more use of this
left-hand side of the panel later on.
| | 05:03 | Now this is not by any means any kind
of major development environment, and it's
| | 05:08 | not even going to prompt you to save anything.
| | 05:10 | So for anything more than a few
lines, I'm going to use a full editor.
| | 05:14 | But for us, experimenting and learning
basic JavaScript syntax, it can come in
| | 05:18 | very handy to just play
around with writing code.
| | Collapse this transcript |
|
|
2. Core JavaScript SyntaxUnderstanding the structure of JavaScript code| 00:00 | So as you see, JavaScript is written as
plain text, like HTML and our CSS, and
| | 00:06 | JavaScript is what's called an
interpreted language, not a compiled language.
| | 00:10 | A lot of other languages need to be
run through a special program called a
| | 00:13 | compiler that takes your code, converts
it into machine code, which can then run
| | 00:18 | on the operating system, but we
don't need to do that with JavaScript.
| | 00:21 | We simply write our code and we
hand it over to the web browser, and the web
| | 00:26 | browser takes care all
interpreting it and running it on the machine.
| | 00:30 | Now, JavaScript is case sensitive.
| | 00:32 | Let me repeat that.
| | 00:33 | JavaScript is case sensitive!
| | 00:36 | If you're coming from a case-insensitive
language, like Visual Basic or Pascal or
| | 00:41 | even old-school HTML, you may want to
write that down and stick it in front of
| | 00:45 | your face for a while,
because it's really important.
| | 00:48 | Now this is often a challenge for web
designers coming from years of handwriting
| | 00:52 | HTML, where, okay, it's good practice to
be consistent, but really if you open a
| | 00:58 | lowercase p tag and close with an
uppercase P tag, it doesn't really matter.
| | 01:04 | Well, it matters here.
| | 01:07 | One will work; the other will not.
| | 01:09 | Mix up the case in a JavaScript
keyword and it will not guess.
| | 01:13 | It will not assume what you
meant. It just won't work.
| | 01:16 | JavaScript will let you be a little
sloppy in some other areas, but case
| | 01:20 | sensitivity is not one of them.
| | 01:23 | Now JavaScript code, like in most
programming languages, is grouped into
| | 01:27 | statements, separate instructions or
commands to say piece by piece what you
| | 01:31 | want your script to do, perhaps change
the color of the piece of text, calculate
| | 01:36 | someone's age, move an image five
pixels to the left, make a menu option
| | 01:40 | disappear or appear, or pop up an alert message.
| | 01:44 | Now what I'm writing here
is obviously not JavaScript;
| | 01:46 | it's what's often called pseudo code,
just plain English lines of what I might
| | 01:50 | want a script to do
without worrying about syntax.
| | 01:54 | A JavaScript statement is typically
written by itself on one line. In the same
| | 01:59 | way that you might use a period or a full stop,
| | 02:02 | to finish a sentence in English, each
JavaScript statement should end with a semicolon.
| | 02:07 | Now because of this, you can put
multiple statements on one line, just separating
| | 02:12 | each of them with the semicolon,
but don't do this--it makes it harder to read,
| | 02:16 | split multiple statements onto multiple lines.
| | 02:20 | In fact, what's more likely is the
opposite situation where if you have a
| | 02:24 | really, really, really long statement,
you can split that across multiple lines
| | 02:29 | to make it easier to read, marking
the end of the full statement with a
| | 02:32 | semicolon, but most of the
time one statement, one line.
| | 02:37 | Now, JavaScript is a
forgiving language about some things.
| | 02:41 | That might sound like a good
thing, but it really isn't.
| | 02:44 | If you're familiar with HTML, you know
you can forget to close a tag and most
| | 02:49 | of the time the page would still work,
but you know this ends up being a bad
| | 02:54 | thing, because it leads to sloppy code, and it
leads to browsers trying to guess what you meant
| | 02:59 | and often different browsers doing
different things with that guess.
| | 03:02 | Now the equivalent here is that in
many cases your JavaScript statement would
| | 03:07 | still work if you left off
the semicolon, but don't.
| | 03:11 | Let's just imagine it's required,
because if you're casual about it, you
| | 03:15 | will run into problems.
| | 03:17 | So we'll always be conscious of using
the semicolon to finish a statement.
| | 03:20 | A JavaScript might be case sensitive,
but it's not sensitive to spaces or line
| | 03:26 | returns between
different pieces of the language.
| | 03:28 | So if I have the statement "Hello world,"
I could also write it like this with a
| | 03:32 | lot of spaces between the
different pieces of the statement.
| | 03:35 | I could even split it onto different lines.
| | 03:38 | You can typically use however many
spaces or line breaks make it readable
| | 03:42 | to you, but the only place spaces
do matter is here inside the double
| | 03:46 | quotes, because it then assumes
that we want to write out Hello, space,
| | 03:50 | space, space world.
| | 03:52 | But other than this, and other than the
idea that you can't put a space in the
| | 03:56 | middle of a word, JavaScript really doesn't care.
| | 03:58 | Now as you're writing code, it's
useful to add comments, so you can add
| | 04:02 | comments to your JavaScript by simply typing
a line with two forward slashes both together.
| | 04:08 | This is like other C-based languages.
| | 04:10 | JavaScript than ignores anything
after the two forward slashes and begins
| | 04:14 | again on the next line.
| | 04:15 | Now, typically you add comments on the
line above the one they're referring
| | 04:20 | to, but you can also add them at the end of
statement as well, and they will be ignored there.
| | 04:25 | You can also comment out multiple lines
by typing a forward slash asterisk, and
| | 04:30 | everything after that is considered a
comment, even if it's a hundred lines later,
| | 04:35 | until you see the flip side,
the asterisk forward slash.
| | 04:37 | Now I only tend to use this to comment
out large chunks of code when testing;
| | 04:43 | everywhere else I use the single-line style.
| | 04:45 | It's a bit more obvious.
| | 04:47 | Now like most programming languages,
the default behavior when JavaScript runs
| | 04:51 | is to start at the first statement and
move down, executing each statement one by one.
| | 04:58 | And the question is, when?
| | 05:00 | And unless you say otherwise, it's as
soon as the browser sees your code, and
| | 05:06 | that can have very interesting
implications, because we can put the script tags
| | 05:12 | just about anywhere in our HTML.
| | 05:14 | We can put it in the head section, in
the body section, in the middle, but let
| | 05:18 | me show you the impact of this.
| | 05:20 | So again, I'm looking at this very simple,
very straightforward HTML page with a
| | 05:24 | little bit of JavaScript in it.
| | 05:25 | I'm going to cut the script tags from
where they were and place them in the head
| | 05:31 | section, and you'll see this a lot.
| | 05:33 | You'll see a lot of script
tags in the head section.
| | 05:35 | I'm then going to save this and double-click
this HTML file to open it up in the browser.
| | 05:42 | Now, notice what it's doing here.
| | 05:44 | The browser is reading our HTML,
and it's going line by line through the HTML.
| | 05:50 | It hits the script tag and is executing
this script, this line, as soon as it gets to it.
| | 05:56 | Now that alert is causing us to pause and
as you can see, the page is actually blank.
| | 06:02 | It's grayed out, but it's completely
blank until I click OK, and then we see the
| | 06:06 | content of the page actually
jump in and fill and be rendered.
| | 06:11 | Now if I take that script tag, cut it
from the head, and move it to the end, save
| | 06:18 | that, run this again,
| | 06:21 | while we get the same JavaScript
behavior, you'll notice that the actual page
| | 06:25 | content has already been rendered
before we then ran our JavaScript.
| | 06:29 | So the position of your JavaScript in
your page really does matter, but by
| | 06:34 | default it will be interpreted and
executed as soon as the browser sees it.
| | 06:39 | Now, okay, on a simple page like this
that's fine, but of course we don't always
| | 06:44 | want to run everything immediately.
| | 06:46 | Okay, sometimes we want to run the code
when the page loads, but sometimes not
| | 06:50 | till the user fills out a form, or
moves their mouse, or hits the Tab key.
| | 06:55 | And we'll do that, as in most
languages, by grouping our code into separate
| | 06:59 | self-contained pieces and then telling
the browser we only want to run them in
| | 07:03 | response to certain events, but that's
another movie and we've got a couple of
| | 07:07 | things to cover first.
| | Collapse this transcript |
| Where to write your JavaScript| 00:00 | Before we get much further, let's
talk a little bit about where our
| | 00:03 | JavaScript should go.
| | 00:05 | You see creating JavaScript like this,
what's referred to as inline code, is okay
| | 00:09 | to get us started but is not
how we're going to continue.
| | 00:12 | The problem with having your JavaScript
mixed in with your HTML is not an issue
| | 00:17 | on a tiny test page like this,
but when you start creating more complex pages
| | 00:22 | your code becomes fragmented.
| | 00:24 | It becomes hard to edit.
| | 00:25 | It becomes hard to maintain.
| | 00:27 | And because you often do the same
thing across dozens or hundreds of pages,
| | 00:32 | you've got duplicated code and if you
make any changes, you might have to make
| | 00:36 | them dozens or hundreds of times.
| | 00:38 | So instead of having it this way, what's
referred to as inline JavaScript, we're
| | 00:43 | going to put our JavaScript in a
separate file like you might do with CSS.
| | 00:48 | It's easier to maintain,
| | 00:49 | it's easier to use across multiple pages,
and as you'll see, it's even easier to write this way.
| | 00:55 | We simply cut our JavaScript from
the HTML and put it in a separate file.
| | 01:00 | Now we don't need to copy across the
script tags; we keep those in the HTML page,
| | 01:05 | because we need them to describe
the link between our HTML page and the
| | 01:10 | JavaScript. And we just use the source
attribute, the SRC attribute, like you might
| | 01:15 | do with say an image tag.
| | 01:16 | Now your JavaScript file is just
text. It could be any file name, but by
| | 01:20 | convention it ends with.js.
| | 01:23 | Now right now these two files would
need to be beside each other in a folder or
| | 01:28 | subfolder, because the SRC, the
source attribute, obeys the same rules as
| | 01:32 | linking to an image or a style sheet file.
| | 01:34 | This could be a relative link.
| | 01:35 | It could be an absolute link.
It could even be on another server.
| | 01:38 | In this course, I'm going to tend
to keep them in the same folder for
| | 01:41 | simplicity. And then we can just
squeeze up the script tag, because there
| | 01:44 | is nothing inside it.
| | 01:46 | Now we have a great division
between our HTML and our JavaScript.
| | 01:50 | Let's talk a little bit more
about the script tag itself.
| | 01:53 | When reading other people's JavaScript,
you're going to very often see this type
| | 01:57 | attribute in your script tag.
| | 01:59 | And this is saying not only this
is script, but this is JavaScript.
| | 02:04 | Officially, it could be a whole range
of different options, and it's hearkening
| | 02:07 | back to the days when we had to worry
about what particular flavor of scripting
| | 02:11 | language we were using.
| | 02:13 | But if you leave it off, every
browser will assume it's JavaScript anyway.
| | 02:17 | Now yes, the type attribute is formerly
required if you're fully complying to the
| | 02:22 | HTML 4 or XHTML spec, but in the HTML5
spec it's officially optional and just
| | 02:28 | defaults to JavaScript.
| | 02:30 | Now some code editors will add the type
attribute automatically, and some others
| | 02:34 | will complain if you don't have it.
| | 02:36 | So it might be easier for you to leave it,
but I have never encountered a single
| | 02:40 | situation while leaving it
off has any impact at all.
| | 02:43 | So I'm in the rather large count
that says these days just leave it off.
| | 02:47 | And next question, where
do you put the script tag?
| | 02:49 | It's very common, as we've said before,
to see the script tag in the head and
| | 02:55 | although this will work,
| | 02:56 | I'm not a big fan of this, because
remember JavaScript is parsed and interpreted
| | 03:00 | as soon as it's hit by the browser,
and that means your JavaScript file could cause
| | 03:04 | a delay in rendering the page.
| | 03:06 | And we really don't want to slow the page down.
| | 03:08 | We want the browser to load the page,
and then we'll have our script come along at the end.
| | 03:11 | Now there might occasionally be a need to
immediately load and process some JavaScript.
| | 03:17 | For example, you might be using
JavaScript to actually create the page content.
| | 03:22 | Then okay, you want it as soon as possible.
But if there is a good rule of thumb,
| | 03:26 | it's to have your script tag not just
in your body section, but at the very
| | 03:30 | bottom just before the closing body tag.
| | 03:33 | Now, if I'm linking to style sheets, I'll
keep those links in the head section so
| | 03:38 | that they do load immediately, but my
general rule is style sheets up at the top,
| | 03:42 | script files down at the bottom.
| | 03:44 | Now, later we might even have multiple
script tags here to link to multiple
| | 03:49 | JavaScript files, and then we could get
concerned about what order they are in,
| | 03:53 | but we'll cross that bridge when we get to it.
| | Collapse this transcript |
| Creating variables| 00:00 | In all programs and all programming
languages we have to keep track of many
| | 00:04 | pieces of data, email addresses, a
date of birth, position of an image on the
| | 00:09 | screen, the current score in a game,
so we create variables to hold that data.
| | 00:14 | A variable is a container.
| | 00:17 | It's us grabbing a little piece of
computer memory and giving it a name, so we
| | 00:22 | can use it while our JavaScript is running.
| | 00:24 | We create it, we name it, we put a value in it,
and then we change the value as we need to.
| | 00:30 | In JavaScript, you create a variable like this.
| | 00:33 | You use the word var, all written in
lowercase, which is part of the JavaScript
| | 00:38 | language, and then the word you want.
| | 00:40 | The name of the variable itself is up to
us, and it should represent the piece of
| | 00:45 | data that we want to hold, in this case
year, but it could be customerEmail, or
| | 00:49 | todaysDate, or while we're experimenting,
just nonsense words like foo, or even
| | 00:54 | single letters like x.
| | 00:56 | The name that you want to use for your
variable must be written as one word, no
| | 01:00 | spaces are allowed, and it can be made
of letters, numbers, the underscore, and
| | 01:06 | the Dollar sign, but you
can't start with a number.
| | 01:10 | So, for example, a variable with the
name 99problems would not be allowed, but a
| | 01:15 | variable with the name
problems99 would be allowed.
| | 01:19 | Now we'll talk more about naming our
variables and what you should call them
| | 01:23 | later on when we talk about style in JavaScript.
| | 01:26 | I'm just going to use simple names for now.
| | 01:29 | So what we're doing with this line of
code is we're just carving out a little
| | 01:34 | area of memory to hold a value.
| | 01:36 | And right now after this line
var year runs, this variable exists.
| | 01:42 | It has a name, year, but it doesn't
have a value. It's regarded as undefined, and
| | 01:46 | undefined has a special meaning in JavaScript.
| | 01:50 | Now there is no real point in
having a variable that stays undefined,
| | 01:53 | so we can define, or set, the initial
value of the variable when we create it.
| | 01:58 | We could do that as two statements:
first, var year to make the variable and
| | 02:03 | then year = 2011 to set it.
| | 02:06 | Now the equal sign here is
setting the variable to the value 2011.
| | 02:11 | It is an instruction.
| | 02:12 | Now, more typically if you're doing
this, you just combine these into one
| | 02:17 | statement, var year = 2011,
to both define it and set its value.
| | 02:22 | Now here is another place where
JavaScript will let you be sloppy and I
| | 02:27 | won't. Technically, the word
var is not even required.
| | 02:32 | In JavaScript, if I write some script
that starts off with this line, JavaScript
| | 02:36 | will go looking for an existing variable
called year, but if it doesn't find it,
| | 02:41 | it will just make it.
| | 02:42 | However, we are always going to
use var when defining our variables.
| | 02:46 | There are a couple of situations where
leaving var off can lead to unexpected
| | 02:50 | behavior, so make a habit of always using it.
| | 02:53 | Now variable names are case sensitive
so var x with lowercase and var x with
| | 02:59 | uppercase would be two different variables.
| | 03:01 | Now you can run into problems
accidentally sometimes here.
| | 03:04 | Let's say we create a variable called
x lowercase and set it equal to 200, and
| | 03:09 | then later in our code we
just want to change it to 210.
| | 03:12 | Well, if I accidentally use an
uppercase X here, I've got a problem: because
| | 03:17 | of the automatic creation of variables from
JavaScript, we now end up with two different ones.
| | 03:22 | And now nothing would give you an error,
and nothing would inform you that this is happening.
| | 03:27 | So be careful when naming your variables.
| | 03:29 | Now if you're creating multiple
variables at the same time, instead of
| | 03:33 | spreading them across multiple lines,
you can create one JavaScript statement
| | 03:38 | and just separate the names of the
variables with commas, and that would give
| | 03:41 | you three variables here.
| | 03:44 | Similarly, if you're creating and
initializing them with these initial values,
| | 03:49 | you can separate those with commas as
well to both create them and set them.
| | 03:55 | So just by running that one line, we get
an area of memory allocated for us with
| | 04:01 | the name that we chose.
| | 04:02 | Now, in many other programming
languages when you define a variable, you don't
| | 04:06 | just give it a name, but you also have
to say exactly what type of information
| | 04:11 | is going to be stored in each
variable. Is it an integer? Is it text?
| | 04:15 | Is it a Boolean value, which just means a
value that's either true or false, and so on.
| | 04:20 | Now once you've chosen the type
you're not allowed to change it, but in
| | 04:24 | JavaScript we don't do that.
| | 04:27 | JavaScript is what's
called a weakly typed language.
| | 04:30 | We don't make an integer variable, or
a text variable, or a Boolean variable.
| | 04:35 | We just use var to create a generic
variable and then simply put whatever type
| | 04:39 | of value we want in it.
| | 04:41 | So if I executed the line var myVariable,
I actually begin with this as undefined.
| | 04:47 | If I then say myVariable = 200,
that variable stores the number in it.
| | 04:52 | If I say myVariable = Hello and the
word Hello in double quotes here, this is a
| | 04:57 | piece of text, what's referred to as a
string, and that just means one or more
| | 05:01 | characters strung together.
| | 05:03 | Now with JavaScript, you can use
either double quotes or you can use single
| | 05:08 | quotes to surround a string of text,
but just don't mix them. Don't open with
| | 05:13 | double quotes and close with single quotes.
| | 05:15 | I tend to use double quotes because
that's more common in other languages, but
| | 05:19 | you'll see both ways. And we can store
Boolean values, which is just a value that
| | 05:24 | can either be true or false.
| | 05:27 | Now with these you do not
need the quotes around them.
| | 05:30 | JavaScript understands the words
true and false written in lowercase.
| | 05:34 | They are considered part
of the JavaScript language.
| | 05:37 | So you can start a variable off as
undefined, then put a number in it, then a
| | 05:41 | string in it, then a Boolean in it.
| | 05:43 | That doesn't mean JavaScript doesn't care
about the type of data you have--it does.
| | 05:48 | It treats numbers differently from
strings and strings differently from Booleans,
| | 05:52 | but any JavaScript variable can hold
any of these values, and more complex data
| | 05:58 | too, including arrays and objects and
even functions, and we're going to go
| | 06:02 | deeper into how they all behave later on.
| | 06:04 | And as you'll see, sometimes you'll need
to ask, "Well, what kind of value is in a
| | 06:09 | particular variable?"
| | 06:10 | Now of course, the point of making
variables is that we're going to use them.
| | 06:15 | We're going to manipulate them, ask
questions of them, but that all begins by
| | 06:19 | knowing how to make them.
| | Collapse this transcript |
| Working with conditional code| 00:00 | Beyond the most basic JavaScript
one-liners, we need to start asking
| | 00:04 | questions, being able to have code
that only runs under certain conditions
| | 00:08 | rather than all the time, and we begin
this with the classic if statement, found
| | 00:13 | in any programming language,
written in JavaScript, as in other C-based
| | 00:17 | languages, using this format.
| | 00:19 | We have the word if, and then we
have a condition inside parentheses and
| | 00:24 | then if that condition is true, we will
execute whatever code is inside the braces here.
| | 00:30 | Now a quick aside for
the folks new to programming.
| | 00:32 | Yes, in programming languages we are
really picky about the symbols we use and
| | 00:37 | about what we call them.
| | 00:38 | So just to be very specific, when I
say parentheses, I mean these; when I say
| | 00:42 | brackets and I usually say square
brackets, I mean these guys; and when I say
| | 00:47 | braces, and I'll usually say
curly braces, I mean these.
| | 00:50 | Now, they serve similar purposes, to
mark where something starts and where it
| | 00:56 | finishes, but they are not interchangeable.
| | 00:58 | Now all of these are always found in pairs.
| | 01:01 | If you have an opening one,
you will need a closing one.
| | 01:05 | It may be several lines later,
but it needs to be there.
| | 01:09 | So back to the if statement.
| | 01:12 | So in this case, the parentheses are
used to mark out whatever our condition is,
| | 01:17 | and the curly braces area used to mark out
what we'll do if that's true, which could
| | 01:22 | be one JavaScript statement,
could be a dozen, could be 100.
| | 01:24 | Now whatever the condition is,
whatever we are asking, whatever is in the
| | 01:29 | parentheses here must
evaluate as true or false.
| | 01:33 | So if I have a variable called a and
I want to see if it's less than 50, I
| | 01:38 | don't care what it is.
| | 01:40 | I don't care if it's 49 or -5 million
or 50.0001; all I want to know is is this
| | 01:47 | true or is it false?
| | 01:49 | Is a less than 50 or isn't it?
| | 01:52 | Is b more than 20 or isn't it?
| | 01:54 | All conditions must boil
down to simply true or false.
| | 01:58 | Now, if I have a variable called c
and I want to check that it's equal to
| | 02:02 | something, to check equality in
JavaScript, as in other C-based languages, I can
| | 02:07 | use the double equals sign.
| | 02:09 | There is no spaces between them. Double equals
is considered a single operator. Now heads up,
| | 02:15 | even for the programmers, JavaScript
has another way of checking equality,
| | 02:20 | the triple equal sign.
| | 02:21 | We will come back and talk about
equality again, but realize for now that if, in a
| | 02:27 | condition, if you're asking if
something is equal to something else, you will
| | 02:31 | never use a single equal sign.
| | 02:33 | As we saw with variables, a single equal
sign is an assignment. It's a command.
| | 02:38 | It sets a value, not checks a value.
| | 02:41 | So we can use double equals or right
now triple equals will do the same thing.
| | 02:44 | Again, we'll come back to this one.
And if I want to check that a variable is not
| | 02:49 | equal another value, it's the
exclamation mark and equal sign,
| | 02:53 | in this case checking that the
variable d is not equal to 100.
| | 02:57 | If that's true, we will execute our code.
| | 03:00 | When you have several statements
surrounded by these curly braces, this is
| | 03:05 | what's referred to as a code block,
and this is all the curly braces do.
| | 03:09 | They group a section of code together.
| | 03:12 | They don't have any other meaning than
that. And as you will see, these blocks can
| | 03:16 | be nested the same way, say, in HTML
you can nest divs inside other divs.
| | 03:21 | Now a quick word about curly braces.
| | 03:23 | When reading other people's code,
you're likely to see them occur in a couple
| | 03:26 | of different styles.
| | 03:27 | I'm jumping across to Firefox with
Firebug here where I have my little
| | 03:32 | JavaScript window open, and I'm declaring
a variable called amount and setting it
| | 03:37 | equal to 500, and then I
have my if statement here.
| | 03:40 | If amount is less than 1000, that needs
to be either true or false, then we will
| | 03:45 | execute whatever's between the
opening and closing curly braces.
| | 03:50 | Now the opening curly brace right now
is right after the condition, and that's
| | 03:54 | probably the classic way that you'll
see these for C and C++ programmers.
| | 03:58 | You might also see the braces on
separate lines so that they line up.
| | 04:03 | People get religious about brace styles.
| | 04:06 | JavaScript of course does not care.
| | 04:08 | This is regarded as insignificant
white space, and it doesn't change the
| | 04:12 | meaning of the code.
| | 04:13 | The most commonly in most sample
code you will download or you will find
| | 04:17 | online, you will see it this way,
| | 04:19 | immediately opening the brace after the
condition but closing it on its own line.
| | 04:23 | If I decide to run this, not
surprisingly, I should have the pop-up box here
| | 04:27 | saying it's less than 1000.
| | 04:29 | Now if you have an if statement and
you only want to then execute one line of
| | 04:35 | code, technically you don't
need to put the braces in.
| | 04:40 | You don't need to define a code block
for one line, but it's good practice to
| | 04:45 | always do it, because if you miss it off,
it's really easy to mess things up if
| | 04:50 | you decide to edit this code
later, so always use the blocks.
| | 04:53 | And we will always be using these
code blocks, even if we only have one
| | 04:58 | JavaScript statement within them.
| | 05:00 | So if this code is executed when the
condition is true, well, what happens if it isn't?
| | 05:03 | If we just leave it like this, nothing.
| | 05:06 | It would skip over the if and begin
on the next line. But if you wanted
| | 05:09 | something else to happen, you can
follow the if with an else statement and in
| | 05:15 | this case have another code
block that runs different code.
| | 05:18 | If the first condition is true, we run
the code in the first block; otherwise, we
| | 05:22 | run the code in the second block.
And you can even nest them inside each other
| | 05:27 | and check a different condition.
| | 05:29 | But don't nest too deep.
| | 05:30 | JavaScript can handle this quite fine,
but lots of nested ifs, say even beyond two
| | 05:35 | levels, is quite difficult
to read and make sense of.
| | 05:37 | If we do have to have more complex logic,
we are going to start breaking things
| | 05:41 | apart into their own functions.
| | Collapse this transcript |
| Working with operators| 00:00 | Just about every statement we will
write is going to involve an operation,
| | 00:04 | moving data from one place to
another, adding, subtracting.
| | 00:07 | Now to perform a lot of these
operations we need operators, and that just means the
| | 00:12 | symbols that we are using
to manipulate our values.
| | 00:15 | The most obvious are
probably the arithmetic operators.
| | 00:19 | We have addition, we have
subtraction, an asterisk for multiplication,
| | 00:23 | forward slash for division.
| | 00:24 | Now you typically see these used along
with the equal sign, and the equal sign is
| | 00:29 | formally called the assignment operator.
| | 00:32 | When we hit the statement we are going
to execute whatever's on the right of
| | 00:35 | the equal sign and use it to assign of the
value to whatever is on the left of the equal sign.
| | 00:41 | So for those of you who are new to
programming, remember that when you see a
| | 00:44 | single equal sign that's not a
polite description; that's a command.
| | 00:48 | We are setting a value. We are assigning.
| | 00:51 | Now you will often see the same variable
being used on both sides of the equal sign.
| | 00:56 | In this case, we are just adding 10 to
the variable called score and storing the
| | 01:00 | result back in score.
| | 01:01 | Now adding to a variable or
subtracting to a variable happens so often that
| | 01:06 | there is actually a shorthand for this.
| | 01:08 | I could write the statement this way.
| | 01:10 | I could also write it this when using
the plus equals operator, meaning add this
| | 01:15 | number to this variable.
| | 01:17 | Note that this is a single operator,
so there is no spaces between the plus and
| | 01:20 | the equals. And if we have a shorthand
for adding to a variable, we also have a
| | 01:25 | shorthand for subtracting a number
for a variable and for multiplying or
| | 01:29 | dividing a variable by a particular number.
| | 01:32 | Now as with most languages, there is
operator precedence in JavaScript, simply
| | 01:38 | meaning some operator symbols are
treated as more important than others.
| | 01:43 | Particularly multiplication and
division are regarded as more important than
| | 01:47 | addition or subtraction.
| | 01:49 | So, if I read the expression on the
right-hand side of the equal sign and just
| | 01:53 | read it in order, left to right, I
would think 5+5 is 10 times 10 is 100, but
| | 01:59 | no, the multiplication is regarded
as more important, so that's done first.
| | 02:03 | 5 multiplied by 10 is 50, then
we add 5, and the result is 55.
| | 02:08 | If I want to impose an order on this, I
simply take the important pieces that I
| | 02:12 | want to be executed together and
surround them with parentheses.
| | 02:16 | In this case, I would take the 5+5
and that would make sure that that was
| | 02:21 | executed independently.
| | 02:23 | Then we multiply it by 10, and the result is 100.
| | 02:26 | And moving on, we have the comparison
operators, back to this idea of equality.
| | 02:32 | Again, if you're checking that
variables are equal to each other or equal to
| | 02:37 | other values, you can use
the double equals operator.
| | 02:40 | Now a classic mistake of
programmers in any C-based language, including
| | 02:46 | JavaScript, is to accidentally use a
single equal sign where you meant to use
| | 02:50 | a double equal sign. So here is an example.
| | 02:54 | I create two variables,
variable a=5, variable b=10.
| | 02:57 | If later on in my code I ask if a=b?
Well, I am using the wrong operator.
| | 03:05 | What's going to happen here is that
the single equal sign is a command.
| | 03:08 | We will hit this, and then we will set
a=b. This then returns true, and the code
| | 03:15 | in the if statement will always be
executed, even when you think it shouldn't be.
| | 03:19 | This is perfectly legal syntax in
JavaScript and in a lot of other languages
| | 03:23 | too, but it can lead to code that just
doesn't work the way you expect, and it's
| | 03:26 | difficult to debug because it's easy to miss.
| | 03:28 | So remember one equal sign is
assignment. You are telling.
| | 03:34 | Two equal signs is the
equality operator. You're asking.
| | 03:38 | And in JavaScript, there is another
equality operator, the three equal signs.
| | 03:45 | Three equal signs is the
strict equality operator.
| | 03:48 | Now what on earth does that mean?
| | 03:50 | Let me show you an example.
| | 03:51 | I am going to open up Firefox.
| | 03:53 | I just have my preferences set to open on a
blank page, and I'll open up the Firebug panel.
| | 03:59 | Make sure I am in the Console and
that I have the whole right-hand pane
| | 04:04 | activated, so I can type some JavaScript in here.
| | 04:07 | You can also do this in an
HTML page or a JavaScript file.
| | 04:14 | So I write some very simple code here.
| | 04:16 | In this code, I have two variables.
| | 04:18 | Variable a starts off with the number 5 and
variable b starts off with the value 5 but
| | 04:24 | as a string, using double quotes.
| | 04:27 | Now I am going to go ahead and run this.
| | 04:30 | So I'm checking if a is equal to b. And
if you notice I must be popping up the
| | 04:36 | alert that says, Yes, they're equal.
| | 04:38 | And here's what's happening. If I use the two equal signs
as the equality check here, they are regarded as equal.
| | 04:46 | The JavaScript engine is checking them
and saying okay, these two variables may
| | 04:50 | not be identical, one is a number and
one is actually a string value, but they
| | 04:55 | have the same value, so I am
going to say this is true.
| | 04:58 | But if I use the three equal signs
here, this is strict equality check.
| | 05:03 | Run that again and the output
here is that they are not equal.
| | 05:07 | The comparison is false.
| | 05:10 | Three equal signs, strict equality, is
going to check that they're the same value
| | 05:15 | and that the same type under the hood,
that they're not just equal, but identical.
| | 05:19 | Now most of the time the double equal sign
and the triple equal sign will behave the same.
| | 05:25 | As an example, if I had created the
second variable just to have the number 5, then if
| | 05:30 | we use the three equal signs, we would
say, yes, they're equal and if we use two
| | 05:35 | equal signs, yes, they're equaled.
| | 05:37 | They are both equal and they are identical.
| | 05:38 | Now most of the time you will find
that the double equals and triple equals
| | 05:44 | could be used interchangeably, though
some JavaScript experts recommend using
| | 05:49 | the triple equal sign all the time
and just never using double equals.
| | 05:52 | I wouldn't go that far, so when I see
a double equal sign in someone else's
| | 05:56 | JavaScript I don't consider it wrong.
But if you were to get into the habit of
| | 06:00 | using triple equals all the time,
that's certainly not a bad habit to get into.
| | 06:04 | So when we are writing, say, an if
statement and we're checking if we have
| | 06:08 | equality, double equals. If we want to
check that something is not equal to, it's
| | 06:13 | the exclamation mark equals,
or we have the triple equals and its
| | 06:17 | counterpart exclamation mark equals
equals, not strictly equal to.
| | 06:23 | We then have the classic greater than
operator, less than operator, greater than
| | 06:27 | or equal to, less than or equal to.
| | 06:30 | And again, all of these must
respond with either true or false.
| | 06:36 | Something is equal or it is not;
something is greater than or it is not;
| | 06:41 | something is strictly equal to or it is not.
| | 06:43 | Now what happens if you
have a few questions to ask?
| | 06:47 | If in a situation that we are
comparing several things, I want to know if a is
| | 06:52 | strictly equal to b and c is
strictly equal to d, how do I write that?
| | 06:57 | Well, what we will use
here is the double ampersand.
| | 07:01 | This means "and," a logical "and."
| | 07:03 | And I say logical "and" there because
some people take "and" as meaning addition.
| | 07:08 | The flip side of this is what if we are
interested in one or the other situation?
| | 07:13 | If the variable a is strictly equal
to the variable b or the variable c is
| | 07:18 | strictly equal to the variable d, we use
the double vertical bar, or pipe symbol.
| | 07:25 | This is the logical or.
| | 07:26 | Now you will often see these kind of
split up with multiple sets of parentheses
| | 07:31 | to make it a bit more explicit
about what you're looking at,
| | 07:34 | in this case, if a is greater than b and
c is less than d. But as ever, the entire
| | 07:41 | condition, the wider set of parentheses
must evaluate as either true or false.
| | 07:48 | If you have several things to check, you
may even split it across multiple lines
| | 07:52 | if you want to make it more readable.
| | 07:54 | It's one of the benefits of
white space being insignificant.
| | 07:57 | Now, a couple of roundabout operators here.
| | 08:00 | We have the modulus, or
remainder operator in JavaScript.
| | 08:05 | This one's a little different. Probably
the classic example here is using it to
| | 08:09 | do something like calculating a leap year.
| | 08:11 | So in this case I create a variable
called year, and it's equal to 2003, and then
| | 08:17 | I create a variable called remainder.
| | 08:19 | I set that equal to year % 4.
| | 08:23 | The % here is the modulus, or remainder operator.
| | 08:26 | What it means is divide the variable
year, 2003, by 4, but don't give me the
| | 08:32 | result, give me the remainder, which
in this case 4 would go into year 500
| | 08:37 | times and the remainder would be 3,
and you will run into this one now and then.
| | 08:42 | Next, we have shorthand
for adding to a variable.
| | 08:46 | Now we have already seen this a little bit.
| | 08:48 | If we have a variable called a
and we want to add 1 to it,
| | 08:51 | I could do it the long way, which would be this.
| | 08:54 | I could do it the shorter way, a+=1.
| | 08:57 | But if I am just interested in adding
1 to a variable, I can also use another
| | 09:02 | operator, which is ++.
| | 09:04 | If you want to get geeky about this,
this is what's called a unary operator,
| | 09:08 | meaning it only needs one thing to act on.
| | 09:11 | Now the plus plus operator, which
increments by 1, can be used either after the
| | 09:17 | variable name or before the variable name,
| | 09:19 | so a++ or ++a. And the flip side is true.
| | 09:24 | We have a=a-1, or a-=1, or a--, or --a, they
all do the same thing. Now by themselves
| | 09:34 | on lines like this, great.
| | 09:36 | But there is actually a tricky difference.
| | 09:38 | So the plus plus and the minus minus can be
used either before the variable name or after.
| | 09:44 | Technically, if you want to get geeky
about it, it's what's called the prefix
| | 09:47 | and postfix versions of those operators.
| | 09:50 | And while they end up doing the same
thing, they do it in a different way, and
| | 09:55 | there is an impact to which one you choose.
| | 09:57 | Let me show you what I mean.
| | 09:58 | Let's say we start off with creating a
variable a and setting it equal to 5.
| | 10:04 | What I am then going to do is
write a statement that says alert(++a).
| | 10:10 | So I want to pop up a message box with
the contents of the variable a, and I'm
| | 10:14 | going to add 1 to it.
| | 10:16 | What happens is using the prefix
version where the plus plus is before the
| | 10:20 | variable we will actually execute that,
and we will increment a before we run this line.
| | 10:27 | So the value of a will be changed to 6 and
then the alert message will pop up saying 6.
| | 10:34 | However, if I go back and do this a
slightly different way, doing an alert with
| | 10:39 | a++, what happens is we will first do
the alert and only then, at the end of the
| | 10:46 | line, will we cause 1 to be added to a.
| | 10:49 | The end result is the same, that the
variable a=6, but the message that we popped
| | 10:55 | up was different, and this is one of
those little things that can cause bugs.
| | 11:00 | So I tend to only use the plus plus and minus
minus on their own statements by themselves.
| | 11:05 | Then it doesn't matter.
| | 11:07 | I know that when I have executed that line
of code it's been incremented or decremented.
| | 11:12 | And finally, the last one that I am
going to talk about is a great little useful
| | 11:17 | one called the ternary operator.
| | 11:19 | That's not a great name,
but there is no better name for it.
| | 11:22 | See, most of our operators are
what are called binary operators.
| | 11:25 | Now it doesn't mean they work on binary code.
| | 11:27 | It just means they work on two elements;
| | 11:29 | there is something on the left and
something on the right, a+b, amount divided by year.
| | 11:35 | They work on two pieces.
| | 11:37 | The unary operator, plus plus, minus minus,
works on one, and ternary works on three.
| | 11:43 | So it actually has two symbols to it,
the question mark and the colon.
| | 11:48 | Now the general format of using
this is that you have a condition.
| | 11:52 | You're asking something.
| | 11:54 | Then you say what happens if this is
true and what happens if this is false.
| | 11:57 | You can actually think of it
as a mini if/else statement.
| | 12:01 | So let me show you an example here.
| | 12:04 | So let's say I define two variables:
var playerOne=500, var playerTwo =600.
| | 12:09 | Now some time later in my code I want
to create a high-score variable and I
| | 12:16 | want to set this equal to
whatever the larger of the first two are.
| | 12:21 | Well, I could write this using an if statement.
| | 12:24 | If playerOne>playerTwo, we will set
highScore=playerOne; otherwise, we will set
| | 12:29 | highScore=playerTwo.
| | 12:31 | So I have got about six lines here
just to set the value of highScore.
| | 12:36 | With the ternary operator, it would let
me take it from six or seven lines to one.
| | 12:41 | What we do is we specify three things:
the condition, question mark, what if it's
| | 12:45 | true, colon, what if it's false.
| | 12:47 | So my condition is playerOne>playerTwo.
| | 12:51 | Like all conditions, this has
to be either true or false.
| | 12:54 | I put the question mark. Then I say if
it's true, I want to return the value of
| | 12:59 | playerOne colon, if it's false, I am
returning the value of playerTwo, semicolon
| | 13:06 | to end the statement.
| | 13:08 | This would allow me to get rid of that if
statement and have the whole thing just on one line.
| | 13:14 | Now we probably won't use this much in this
course, but you will see it from time to time,
| | 13:18 | so I want to be able to recognize it
when you do see it. And this has given us
| | 13:22 | plenty of operators and definitely will
be enough to get us moving and building
| | 13:25 | some useful logic in our code.
| | Collapse this transcript |
| Sending messages to the console| 00:00 | I've been using this alert box because
we need some way of getting a message out
| | 00:05 | of JavaScript, but it is kind of
annoying, particularly if I have several of them,
| | 00:10 | because it requires that I click the OK
button to dismiss it. And it's certainly
| | 00:14 | not going to be what we want to do much
more except in real alert circumstances.
| | 00:19 | But luckily, we have Firebug, and having
Firebug gives us something very useful here.
| | 00:26 | Instead of alert, from now on what
I'm going to do when I want the same
| | 00:30 | equivalent is I am going to change that to
console.log, leaving everything else the same.
| | 00:35 | This is all written in lowercase.
| | 00:38 | As you can see, I have three
statements here that all call console.log.
| | 00:42 | Now if I run this one again, instead
of having the alert box pop up in the
| | 00:46 | page section, I'm actually getting a
pop-up over here in the actual console,
| | 00:51 | which is part of Firebug.
| | 00:53 | Console.log is not officially
part of the JavaScript language.
| | 00:56 | It's an add-on that Firebug
is bringing to the party,
| | 00:59 | although it does work in other
JavaScript debuggers like the ones you can get in
| | 01:03 | Internet Explorer and Safari.
| | 01:05 | Now what that does mean is that unlike
an alert message, if you don't have the
| | 01:09 | Firebug console open, you are not
going to see it, but that's okay.
| | 01:13 | It's intended for us as writers of
JavaScript; it's not for the end user.
| | 01:18 | They should never see it,
but we certainly want it.
| | 01:21 | So we can write out a string
as a message to the console.
| | 01:25 | We could write out a variable like
the variable I have defined just a step
| | 01:28 | above, which is foo.
| | 01:30 | I can write down multiple variables just
by separating them with commas, and over
| | 01:35 | on the left-hand side I am just going
to hit the Clear button to clear the
| | 01:38 | console, run this again, and I can
see the output that I'm having here.
| | 01:42 | Now, a log message is just a log message.
| | 01:46 | This could be a good message, could
be a bad message, could be informative.
| | 01:51 | We can make that behavior more apparent
if we know there's an error, or we know
| | 01:55 | it's informational, by changing the
word log to one of four other words.
| | 02:00 | We could change log to debug.
| | 02:03 | Now I will just comment
out the other lines right now.
| | 02:07 | Clear the console on the left and run it.
| | 02:09 | Not much of a difference on that one.
| | 02:12 | Change debug to info.
| | 02:15 | Now I get the little I icon here.
| | 02:18 | Change info to warn.
| | 02:21 | Now I get the yellow and the exclamations
mark. Or change console to error and run that,
| | 02:28 | and we actually get the error message here.
| | 02:30 | It's the same message,
but different icons for them.
| | 02:33 | Though note, if you do have an error, you
will also now get it in the status bar
| | 02:37 | as well, but for the most part we
will just be doing console.log, the most
| | 02:43 | straightforward way of doing this.
| | 02:45 | We can do a few other things
with the console, as we'll see later, like
| | 02:49 | measuring performance and how long a
script is taking to run, but if nothing
| | 02:54 | else, console.log is going to come in
immensely useful for us to understand
| | 02:57 | our own code better.
| | Collapse this transcript |
| Working with loops| 00:01 | Very quickly we will find ourselves
writing code that we want to have happen
| | 00:04 | multiple times. Whether that's
grabbing every paragraph in a page so we can
| | 00:10 | change the background color of it,
hiding everything in a menuing system,
| | 00:14 | we will realize there's code we want repeated.
| | 00:17 | Well, rather than write it out multiple
times, I'd rather write it once and be
| | 00:21 | able to say, "Repeat this five times," or
"Repeat this 5,000 times," or "Just keep on
| | 00:27 | repeating till I tell you otherwise,"
| | 00:30 | perhaps go through every single form
field on the web page or process every link
| | 00:36 | on a web page in some way, and this is
what we do when we are creating loops.
| | 00:41 | You will also hear this referred to as iteration.
| | 00:44 | The main issue with any loop is not when
to loop--looping is easy--it's when to stop.
| | 00:50 | If we need to loop 200
times, who is keeping track?
| | 00:53 | If we need to loop until we are told to stop,
where is the code to figure out how to stop?
| | 01:00 | But let's first figure out
the most basic kind of loop.
| | 01:03 | Well, we've seen if statements
before, and this is all I have here.
| | 01:06 | If this condition is true in the
parentheses, we will execute the code
| | 01:11 | inside the curly braces.
| | 01:13 | Now if all I do here is replace the
if with the word while, we have a loop.
| | 01:18 | It could be a one line in this code block,
there could be 100 lines in this code block;
| | 01:24 | whatever is in the block gets
done every time the loop goes around.
| | 01:29 | So we start to run this code.
| | 01:30 | We will create a variable
called a, set it equal to 1.
| | 01:33 | We will come down to this while part.
| | 01:36 | I will check the condition, which in
this case is a < 10. Yes, that's true.
| | 01:40 | I'll jump into the body of the block,
| | 01:42 | execute any lines of code that are there.
| | 01:45 | We will hit the end.
| | 01:46 | We will hit the closing brace,
and that will jump as back up to the while
| | 01:50 | statement again, where we will ask the
same question, is a < 10? Well, yes it is.
| | 01:55 | It's still 1, in which case
we'll continue on processing.
| | 01:59 | What we've done here is create a loop.
| | 02:02 | We have actually created an infinite loop,
which isn't all that pleasant. It's a bad thing.
| | 02:07 | This would never end. a is always going to
be less than 10 because we never change it.
| | 02:12 | So a very common thing that we need
to do in most loops is make sure that
| | 02:17 | whatever we are doing to keep
track of the loop is being incremented.
| | 02:22 | So this time I've got an a++ at
the end of the body of the loop.
| | 02:28 | So with the of the iteration in place,
we will start to increment a every time
| | 02:31 | we go around the loop, and we will keep on going.
| | 02:34 | And at some point, what's going to
happen is a will be incremented to 10.
| | 02:39 | We will come back to the while.
| | 02:41 | This will evaluate as false, and then what
we'll just do is we will jump out of the loop.
| | 02:47 | We will jump right to the end,
and we will continue processing whatever
| | 02:50 | code happens afterwards.
| | 02:51 | Now there is a variant of the
while loop called the do while loop.
| | 02:58 | What this does is keeps the same
basic format, but we actually move the
| | 03:02 | condition to the end.
| | 03:04 | So instead of while a is less than
10 being at the start of the block,
| | 03:09 | it's actually at the end of the block,
and because of that, we actually need a
| | 03:13 | semicolon at the end of the do while.
| | 03:15 | Now the big difference with this is
if you have a do while, the block will
| | 03:20 | always be executed, at least once, even
if we started off by setting the variable
| | 03:26 | a equal to 100. And our condition here
is asking while a is less than 10, we are
| | 03:31 | going to execute the do block once
before we even check the condition.
| | 03:35 | So it will happen at least once. To let
you know, while loops are much more common
| | 03:41 | than these do while loop, and the code
I have written over the years I guess
| | 03:44 | that I write at least 100 whiles for every do.
| | 03:48 | In most loops it's expected to check
the condition before entering the loop, and
| | 03:52 | it's more readable that way too.
| | 03:53 | Now in many loops a pattern emerges.
If I look at a while loop here, I could
| | 04:00 | have a lot of stuff going on in this
loop, but I always have to have several
| | 04:05 | pieces in place, regardless of what I am doing.
| | 04:09 | For a start, I need to have something
that keeps track of where I am in the
| | 04:13 | loop, so very typically, before we hit
the while loop, we will create an index
| | 04:17 | variable or a counter variable.
In this case we will call it i--i is a very
| | 04:21 | common name for an index.
| | 04:23 | So we set up the index, or the counter.
| | 04:26 | We then have to have a
place that checks the condition,
| | 04:28 | how do we know whether to keep going
through the loop or not, and then in most
| | 04:32 | cases we have to increment the index at the end.
| | 04:35 | So regardless of what we're doing,
we need these three pieces in place.
| | 04:40 | Set up the index, check the condition,
increment the index, and this is so common
| | 04:45 | that there is even a
shorthand way of doing this,
| | 04:48 | a thing that brings all
these together, the for loop.
| | 04:53 | With this, you actually bring those of
three pieces together inside the parentheses.
| | 04:59 | They are all there at the top.
| | 05:00 | So regardless of what's in your
loop, again it doesn't really matter.
| | 05:04 | Whatever is between the braces will be
executed, whether it's simple or complex,
| | 05:08 | but the loop itself has three pieces.
| | 05:11 | We set up the index, so in this case
var i=1. Then there is semicolon. Then we
| | 05:18 | check the condition, i is less than 10,
and then, even though it's right at the
| | 05:22 | top, this is the incrementer.
This happens at the end of every loop.
| | 05:27 | Now we don't have to go up by 1.
| | 05:29 | You could go up by 4 or 17 or
150 every time if you wanted.
| | 05:32 | So this is very readable because
everything about the loop is right there at the top.
| | 05:38 | You don't have to look outside the
loop for the index, nor scan inside the
| | 05:42 | loop for the increment.
| | 05:44 | So the for loop is a very
common way of doing this.
| | 05:46 | Now, next up is a couple of words
you'll occasionally run into, not as much as
| | 05:52 | the whiles and the fors,
but it's worthwhile knowing about them,
| | 05:55 | a word called break.
| | 05:58 | Break is a word that will
jump us out of the loop.
| | 06:02 | So let's say we start running
our code and we hit this loop.
| | 06:04 | We hit it for the first time through.
| | 06:06 | We set up the index equal to 1.
| | 06:08 | We run the check. Is that
less than 5000? Yes, it is.
| | 06:11 | We start to move through the code.
| | 06:13 | We will hit this if segment, for example,
and it will say is i=101? No, it isn't.
| | 06:18 | So we will skip past that code block
and continue on, hit the end of the
| | 06:23 | loop, go back up, check the condition again,
yes, i is still less than 5000, continue on.
| | 06:30 | Now, at some point what's going to
happen is i will be 101. We will hit break.
| | 06:34 | As soon as we hit break, we are
basically manually saying we are done.
| | 06:39 | We jump completely out of the loop,
and we continue on, regardless of what the
| | 06:43 | condition was at the top, regardless of
where our counter was. If we say break,
| | 06:47 | we are done with the loop.
| | 06:51 | And continue is along the same
lines but not quite as drastic.
| | 06:56 | Let's say in this loop,
however I've got it set up,
| | 06:59 | I've got some pieces of code.
| | 07:01 | We are doing some stuff.
We are checking some options.
| | 07:03 | We are doing a second set of stuff.
| | 07:05 | Well, as we move through the code, if I
check this if statement and my counter
| | 07:10 | divided by 5 leaves a remainder of 0,
| | 07:12 | I'll hit that continue; but if it isn't,
I will just jump straight ahead and
| | 07:16 | keep going on the second part of the loop.
| | 07:19 | Now at some point again we will jump back.
| | 07:21 | We will check it, we will start
processing, but if ever at any point I actually
| | 07:25 | hit the word continue, that
doesn't mean jump out of the loop;
| | 07:29 | it means jump back up and
check the condition again.
| | 07:33 | Don't continue any further
with this iteration, just this one.
| | 07:37 | We are not done with the entire loop,
but we are done with this time around.
| | 07:42 | So we jump right back up, check the
condition again, and then start to process.
| | 07:46 | So continue moves us back up to the top.
| | 07:49 | Break moves us out
beyond the bottom of the loop.
| | 07:52 | Now, you won't need continue or break in
most loops, but you will see them from
| | 07:57 | time to time, and you
need to know what they mean.
| | Collapse this transcript |
| Creating functions| 00:01 | As we start to add more code, we want to
make sure that it doesn't get messy and
| | 00:04 | hard to read, so as with all languages,
we are going to break apart large amounts
| | 00:09 | of JavaScript into
smaller reusable modular pieces.
| | 00:14 | All we are doing is taking several
statements, wrapping them up, and giving them
| | 00:18 | a name, and that means
we are creating functions.
| | 00:21 | In other languages, these might be
called modules or subroutines, but in
| | 00:25 | JavaScript it's functions.
| | 00:28 | To make one, we take the
code that we want to enclose--
| | 00:31 | this could be one line, it
could be a hundred lines--
| | 00:34 | we surround it with curly braces to
create a code block to say where this
| | 00:38 | function starts and ends.
| | 00:40 | We need to say what this is, so we
actually use the JavaScript word 'function
| | 00:43 | all lowercase, and because we could have
dozens or hundreds of these, we also give it a name.
| | 00:49 | This part, like variables, is up to us.
| | 00:52 | The name has to be one word.
| | 00:54 | There can't be any spaces.
| | 00:55 | You can use letters, numbers, Dollar
sign, and underscore, but you can't
| | 00:59 | start with a number. And the function name
should simply be descriptive of what it does.
| | 01:05 | I will just be generic right now.
And then after the name of the function we
| | 01:11 | need to have opening and closing parentheses.
| | 01:14 | These say whether this function expects
to have data passed into it, and in this
| | 01:18 | case empty parentheses means no, it
doesn't. Now after the function is declared,
| | 01:24 | then we can call it.
| | 01:26 | Sometime in our code we can use the
name of the function with the opening and
| | 01:30 | closing parentheses, semicolon--because
it is a full statement--and all the code
| | 01:35 | in the function will be executed.
| | 01:38 | We could do it again. We could do it again.
| | 01:39 | Now, note that as soon as you put your
code in a function, it won't execute.
| | 01:46 | It won't run unless you explicitly call it.
| | 01:50 | Now as you start to write files of
JavaScript, you'll end up having a lot of
| | 01:54 | functions, and it doesn't officially
matter where you put them in your file,
| | 01:59 | because the JavaScript engine will first
do a quick scan of your code and figure
| | 02:04 | out what functions exist
before it tries to run anything.
| | 02:07 | But it's a best practice to define
your functions before you call them.
| | 02:11 | So in this case, for example, I
have got the first line of code saying
| | 02:14 | myFunction, but myFunction isn't
declared till afterwards, which then calls
| | 02:19 | myOtherFunction, which itself
isn't declared till after that.
| | 02:22 | It's a better practice to rearrange
them so that functions are defined and
| | 02:27 | declared before you use them.
| | 02:30 | You don't have to, but it
makes for more readable code.
| | 02:33 | Typically, that just means you are going
to define all your functions up at the
| | 02:37 | top of your JavaScript file.
| | 02:38 | It's very common to create
functions that expect parameters,
| | 02:43 | they expect to be passed information.
| | 02:46 | Now to do this, we take our
parentheses and we put our parameters in there.
| | 02:52 | We say how many pieces of information are
going to be passed and what do I want to call them?
| | 02:56 | We don't need the word var.
| | 02:58 | I am just saying here I expect to be
passed one piece of information and I am
| | 03:02 | going to call it x. So in the code
inside myFunction, I will have this variable
| | 03:07 | called x that I can play around with.
| | 03:10 | Or if I want two, three, four,
parameters, I just separate them with commas.
| | 03:15 | You call them whatever you want.
| | 03:16 | It's the same rules as variable naming.
| | 03:19 | So defining a function that takes X,Y
means that inside the code I can just
| | 03:25 | treat X and Y as if they exist, in this
case making a new variable from them.
| | 03:31 | Whatever is passed in I will multiply
together, and then I will log out the result.
| | 03:36 | And then again later in the code I
can call this function. First off, I am
| | 03:40 | passing in two number. Then I can
call it again, pass in a couple of
| | 03:43 | different numbers, and so on.
| | 03:46 | Now if the format looks familiar,
that's because we're using this when we use
| | 03:50 | that alert, or we when we use console.log.
| | 03:53 | Alert is a built-in function in JavaScript.
| | 03:56 | It takes a long piece of information;
| | 03:58 | in this case, we are passing in a string.
| | 04:01 | And we can optionally return values.
| | 04:03 | Not only can the function accept
information, but we can also send some back, and
| | 04:10 | you can do one or the other, or both, or neither.
| | 04:13 | If I want to return the information,
all I use is the word return and then
| | 04:18 | pass back a variable, or a literal, like
a string literal in double quotes, or a
| | 04:24 | number--it's up to you.
| | 04:26 | Those of you who come from other
programming languages might think, "Well, surely
| | 04:29 | the function has to be defined
differently if we return a value," and in
| | 04:33 | JavaScript, no it doesn't. This is all we do.
| | 04:37 | You don't have to return anything
from a function. It's up to you.
| | 04:39 | Now what this format means is that
later on I could use this function to
| | 04:45 | create a result. And in fact in the
last line here, I am creating a new
| | 04:49 | variable and setting it equal to whatever
is returned from passing in the numbers
| | 04:54 | 6 and 9 into my function.
| | 04:57 | Now if a function does return a value
and you don't do anything with it, you are
| | 05:00 | just calling the function.
That will just be ignored.
| | 05:03 | Now one of the usual issues with
functions that take parameters is what happens
| | 05:10 | if you get something wrong with them?
| | 05:11 | What happens if you pass the
wrong amount of information in there?
| | 05:15 | Let's say we have a function
defined called calculateLoan.
| | 05:17 | This takes four parameters--amount,
months, interest, and name--and it presumably
| | 05:21 | does something with them
inside the body of the code.
| | 05:24 | The way that we should call it is just
by passing those four parameters in order,
| | 05:31 | and inside our function, when it runs, we
will have amount equal to 10,000, months
| | 05:35 | equal to 60, interest equal to 7,
and name equal to Sam Jones.
| | 05:40 | Now if I call myFunction and I pass
in an extra parameter here, in a lot of
| | 05:46 | other programming languages this
would break your code; in JavaScript it
| | 05:50 | will just ignore it.
| | 05:51 | That extra one we drop off the end.
We are effectively just running the
| | 05:54 | function just fine.
| | 05:55 | And the flip side of that, what
happens if I pass in too few parameters?
| | 06:00 | What will happen is that the
missing one will be passed as undefined.
| | 06:06 | interest and name in this
case will be undefined variables.
| | 06:10 | Now your function code might be able
to deal with that, and it might not.
| | 06:15 | So it doesn't necessarily mean it
will work, but this is what will happen.
| | 06:19 | And one last thing, we are going to talk
about something called variable scope here.
| | 06:23 | Now, scope of a variable simply
means where is this variable visible?
| | 06:28 | What part of your code can see it,
what part of your code can use it?
| | 06:31 | So, I have got a function
declared here called simpleFunction.
| | 06:35 | It has got some code in it, and then we have a
line that declares a variable foo=500.
| | 06:41 | We then have console.log foo and if
we call this variable, it's going to
| | 06:46 | output 500 to the console.
| | 06:48 | But let's say right after I call this
variable, I then write another line of
| | 06:53 | code that says console.log(foo),
and then I run console.log(foo), trying to write
| | 06:58 | out the contents of that foo variable.
| | 07:01 | I know this function has already run,
so surely I can write it out. But no, what
| | 07:05 | I get here is the message undefined
because outside the function, as far as
| | 07:10 | JavaScript is concerned, foo doesn't exist.
| | 07:14 | That's because when we use the word
var inside a function definition, this
| | 07:19 | creates a variable that's
known as a local variable.
| | 07:22 | It only exists and is only
relevant inside the function itself.
| | 07:28 | If I needed to have a variable that
was visible throughout my entire file of
| | 07:32 | code, what I'd do is I would
declare foo outside the function.
| | 07:37 | This now becomes what's called a global
variable if it's declared at the absolute
| | 07:41 | top level and outside
any function that you have.
| | 07:45 | Then what I need to do inside the
function is I don't need to define it again, so
| | 07:48 | I am not using a word var.
| | 07:50 | foo can be set to 500.
| | 07:52 | We can write it out inside the function,
and we can write it out outside the function.
| | 07:56 | Now, usually when you're declaring
variables inside a function, you only want to
| | 08:01 | access them inside the functions,
| | 08:03 | so using var is absolutely fine,
but just be aware that you have this concept
| | 08:07 | of local variables with functions.
And for those of you coming from other
| | 08:12 | languages with variable scope, know that this is
only relevant with JavaScript inside functions.
| | 08:17 | This doesn't apply to other code
blocks like loops and if statements and so on.
| | 08:22 | It's a very simple split.
| | 08:24 | You use var inside the function,
| | 08:26 | it only exits inside the function;
otherwise, it's available everywhere.
| | Collapse this transcript |
|
|
3. Types and ObjectsWorking with arrays| 00:00 | So we've seen how to create variables.
| | 00:02 | We use the word var, we give it a name,
and then we can use the equal sign
| | 00:07 | to give it a value.
| | 00:08 | That could be a number, that could
be a string, that could be a Boolean.
| | 00:12 | What we can also do is create arrays.
| | 00:15 | An array is a single
variable that holds multiple values.
| | 00:20 | You create it quite similarly
to creating a normal variable.
| | 00:23 | I'm going to make one
here called multipleValues.
| | 00:26 | You can call it anything you'd like.
| | 00:28 | But to tell JavaScript this is an array,
there are a few ways to do it, but the
| | 00:31 | easiest one is this:
| | 00:33 | var multipleValues = opening square
bracket, closing square bracket.
| | 00:38 | And this is the indicator
that we're dealing with an array.
| | 00:41 | When you see the square brackets, it's a
pretty good indicator you've got an array.
| | 00:46 | This line simply creates a single
variable called multipleValues that you can put
| | 00:52 | several things inside.
| | 00:53 | Well, how do you do that?
| | 00:55 | Using the square brackets again.
| | 00:58 | If we want this array to hold multiple
values, we need to be able to say which
| | 01:02 | one are we dealing with, so we use an index.
| | 01:05 | And I'm saying here I want the
index at 0 to be equal to the value 50.
| | 01:10 | I want the index at 1 to
be equal to the value 60.
| | 01:13 | I can say the index of 2
is equal to the value Mouse.
| | 01:17 | And notice that what I can
do is I can put in a number,
| | 01:20 | I can put in a string,
| | 01:22 | I could put in a Boolean;
| | 01:23 | it doesn't matter what kind of data
you're putting in at the different slots in
| | 01:28 | the array, but all of them
are accessed through the index.
| | 01:31 | That's whether you're setting these values,
| | 01:33 | that's whether you're getting these values.
| | 01:35 | And arrays in JavaScript use
what's called a zero-based index.
| | 01:38 | The first entry is at
position 0, not position 1.
| | 01:42 | And that's very common with most languages.
| | 01:45 | What we can then do is use the same
format to get to the contents of the array.
| | 01:50 | So if I want to write out a console.log
message, I want to get the value that's
| | 01:54 | at position 2 in the
array called multipleValues,
| | 01:57 | I use the square brackets and
it writes out the word Mouse.
| | 02:00 | So if this is the way that
we write arrays, it's okay.
| | 02:04 | It's not too bad, but it would be nice
if there was something a little quicker,
| | 02:06 | and in fact there is.
| | 02:07 | There is a shorthand method for doing it.
| | 02:10 | We use the square brackets and we just
load it up with those initial values,
| | 02:15 | in this case, 50, 60,
Mouse, inside double quotes.
| | 02:19 | And it will automatically put them in at
position 0, position 1, and position 2.
| | 02:24 | You could then come along and add on
position 3, position 4, and so on, but it's
| | 02:29 | always a zero-based index.
| | 02:31 | Now, although this is my favorite way of
saying to JavaScript, "Hey, I'm creating
| | 02:36 | a variable that should be an array,"
| | 02:38 | there are actually multiple ways to
write this, and there's multiple ways you'll
| | 02:41 | see it when you're reading other people's code.
| | 02:43 | An equivalent way is this: var multipleValues =.
| | 02:47 | We use the word new and Array,
Array with an uppercase A here.
| | 02:51 | Now for those of you coming from other
languages, you might be familiar with
| | 02:54 | this kind of format.
| | 02:55 | That's because arrays are objects.
| | 02:57 | They are a special kind of value that we're
going to have a lot of dealings with shortly.
| | 03:02 | And although this format saying =
new Array will work, you don't have to
| | 03:06 | even have the word new.
| | 03:08 | You could just say this as well. All of
these are exactly equivalent to each other.
| | 03:11 | Now for those of you coming from other
languages, you might be wondering what is
| | 03:16 | the size of the array, how does
JavaScript know how big this array is?
| | 03:19 | Well, we can officially create it with a size/
| | 03:23 | In this case, I'm saying the array
should have 5 slots, 0-4, but all arrays in
| | 03:28 | JavaScript are dynamic.
| | 03:29 | They can be as big as you want them to be.
| | 03:32 | If you want something to exist at
position 5, you simply load it into position 5.
| | 03:36 | If you want it to exist at position
100, you load it into position 100.
| | 03:40 | While there is a theoretical fixed
limit to the size that an array can get to,
| | 03:45 | you're never going to run into to it.
| | 03:47 | So my favorite way is just the
square brackets by themselves.
| | 03:51 | I think that's the most
straightforward way of doing it.
| | 03:53 | Now because arrays are objects, they
have properties, and properties means
| | 03:59 | information that we can get to about them.
| | 04:01 | So if I write a line of code that
creates an array and loads it up with some
| | 04:06 | initial values, as in this case, what I
can actually do is use the name of the array--
| | 04:10 | in this case multipleValues--then a dot,
and then I can access the length property--
| | 04:16 | it's information about the array.
| | 04:19 | So in this case, I can write out a
message that says the length of this array is 5.
| | 04:23 | We have five elements in it.
| | 04:25 | Now, the highest index might be 4.
| | 04:27 | We're going to 0, 1, 2, 3, 4, but there
are five elements in there. The length is 5.
| | 04:32 | And because arrays are
objects, they also have methods.
| | 04:35 | Now what does that mean?
Well, we know how to call a function.
| | 04:39 | We use the name of the function,
| | 04:40 | we use the parentheses, and optionally
pass in any parameters that function requires.
| | 04:45 | Well, a method is a
function that belongs to an object.
| | 04:50 | So if we've created an array or
created another kind of object, as we'll see
| | 04:54 | shortly, we can use the name of that
object, then a dot, then the name of the
| | 05:00 | method to call a method. Here's an example.
| | 05:03 | So I create an array with five values in it.
| | 05:07 | I've got this object and
it's called multipleValues.
| | 05:10 | What I can then do is say the name of the
object, dot, and then the name of the method.
| | 05:15 | It's like a function that belongs to it.
| | 05:17 | Well, arrays have built-in methods.
| | 05:19 | We've got reverse as one of them.
| | 05:22 | In fact, when I call reverse on this
array, what it's going to do is give
| | 05:26 | me another array, and I can use the result
of that to actually create a new variable,
| | 05:31 | in this case var
reversedValues, which is also an array.
| | 05:35 | So.reverse() is a method of the array
object, as is.join(), which would join two
| | 05:41 | together, as is.sort(), and I call
them all using this dot operator.
| | 05:46 | But by calling.reverse(), I have this
new reversedValues array, and I could
| | 05:51 | actually call the methods of it.
| | 05:53 | So I could write out console.log
( reversedValues.join() ) which is a method of
| | 05:58 | array, and that will actually join
all the values in the array together and
| | 06:02 | output them as a single string,
| | 06:04 | in this case, writing the contents of it,
which are the reversed values, back out.
| | 06:09 | These are obviously very simple examples.
| | 06:11 | We'll actually see some
practical ones as we go forward.
| | 06:15 | But the fact that arrays are objects
just means we can ask them to do things,
| | 06:19 | and very useful things in a lot of cases.
| | 06:21 | If you're new to programming, you might
be tempted to think of arrays as being
| | 06:25 | esoteric things you're not
really going to use all that much.
| | 06:28 | Well, arrays are everywhere in JavaScript.
| | 06:31 | You won't be able to get away from them.
| | 06:33 | You may create some yourself,
but a lot of them you'll be given.
| | 06:38 | You'll have to deal with them.
| | 06:39 | For example, you might at some point
want to write a little line of JavaScript
| | 06:44 | that says, "I want to know how many
anchor tags exist on the page, how many links
| | 06:48 | do I have, or how many paragraphs
do I have, or how many h3s do I have?"
| | 06:53 | Well, what we can do to get that is called the
| | 06:55 | document.getElementsByTagName method.
| | 06:59 | And we'll get into this a little later.
| | 07:01 | We haven't seen it yet.
| | 07:02 | But this is a built-in ability of
JavaScript to scan through our HTML, grab, in
| | 07:09 | this case, everything that has an a tag,
an anchor tag, and return it to us.
| | 07:14 | I could also ask for all the paragraphs, so
all the p tags, or all the h1 tags, or h2s, or h3s.
| | 07:19 | And what I'll get when I call this is an array.
| | 07:24 | So whether there are four links on the
page or a dozen or a hundred, I'll have
| | 07:28 | an array to deal with.
| | 07:30 | So whether you're asking, give me all the
links that exist on the page, or you're
| | 07:34 | wanting to go through all the form
fields that exist on a web form, arrays are
| | 07:39 | going to be your friends.
| | 07:40 | You are going to have to deal with these.
| | 07:42 | They are zero-based in JavaScript.
| | 07:44 | They are dynamic, meaning that
you can change them very easily.
| | 07:48 | You don't have to use special code to do that.
| | 07:51 | You're always going to see the
square brackets to deal with them.
| | 07:54 | That's always that identifier to
you that you're dealing with an array.
| | Collapse this transcript |
| Working with numbers| 00:00 | Working with numbers comes easily in JavaScript.
| | 00:03 | We've already done this.
We can create variables and put numbers in them.
| | 00:08 | And like any language, we have
the notion of numeric variables,
| | 00:12 | we have the notion of numeric literals.
| | 00:14 | In this case, just the value 200
written in your code is a numeric literal.
| | 00:18 | But if you're coming from another
programming language, you're likely to be
| | 00:21 | thinking, "What kind of number is
this. What kind of variable is this?
| | 00:25 | Is this an integer, is it a floating-
point number, what kind of number is it?
| | 00:30 | We don't have to ask those questions
in JavaScript because internally all
| | 00:34 | JavaScript numbers are 64-
bit floating-point numbers.
| | 00:37 | That's how they're stored under the hood.
| | 00:39 | So you don't concern yourself whether
it's an integer or a small integer or a
| | 00:44 | large integer and so on.
| | 00:45 | Now if you're familiar with floating-
point arithmetic, you'll know that you can
| | 00:49 | have issues with that.
| | 00:51 | In practice, that doesn't tend to be a
problem in JavaScript because most people
| | 00:55 | aren't really doing complicated
financial calculations in client-side code.
| | 01:00 | But yes, JavaScript numbers are
floating-point numbers and all the usual
| | 01:04 | rules apply to that.
| | 01:06 | But if you want to store something in a
JavaScript variable that has something
| | 01:09 | after the decimal point, you simply write it.
| | 01:12 | No special formatting is
needed. It's very easy.
| | 01:15 | However, there are a couple more
things we need to talk about with numbers.
| | 01:18 | One thing that you need to be aware of
is just the behavior that happens when
| | 01:22 | variables have certain values in them.
| | 01:24 | So let's say we start off with a couple
of variables here, var foo and var bar,
| | 01:28 | both equal to the number 5.
| | 01:31 | I can tell it's the number
because there's no quotes around it.
| | 01:34 | And we write out console.log. It's foo+bar.
| | 01:36 | We will write out, not
surprisingly, the number 10.
| | 01:40 | If on the other hand, we say var foo = 5
and var bar = 5, these are strings.
| | 01:45 | They're surrounded in the double
quotes, or the single quotes will work too.
| | 01:49 | The console.log message, while it
looks exactly the same, the Plus sign is
| | 01:54 | going to do concatenation.
| | 01:55 | It's just going to slam these two
together because it thinks you want to
| | 01:59 | treat them as a string.
| | 02:01 | Now, sometimes you do. Say, for example, that
these are holding area codes and phone numbers.
| | 02:07 | You might want to concatenate them together
instead of adding the numeric values together.
| | 02:12 | But just be aware of that behavior.
| | 02:14 | More likely you're interested in
what happens in this kind of situation.
| | 02:18 | What happens if one of them is a
number and one of them is a string?
| | 02:21 | Well, in this case it's
going to do concatenation.
| | 02:23 | If any part of it is a string, it's going
to treat the whole operation as a string.
| | 02:27 | But that can lead us into
more significant issues.
| | 02:30 | What happens if one of these
variables is a string and we're trying to do
| | 02:33 | something with it that just doesn't make sense?
| | 02:35 | In this case, we're trying
to do console.log(foo*bar).
| | 02:40 | We're using the asterisk.
| | 02:41 | So 5 multiplied by b,
well, what's that going to do?
| | 02:44 | Well, actually, what it's going
to do here is evaluate as NaN--
| | 02:49 | that's an uppercase N, lowercase a,
uppercase N--which is "Not a Number."
| | 02:53 | This is a special meaning in JavaScript.
| | 02:56 | It's telling me here this expression
did not make sense, and sometimes we need
| | 03:00 | to know this, because think about this situation.
| | 03:02 | Here's the situation we
might be more concerned about.
| | 03:05 | Let's say we know we're going to get a variable.
| | 03:07 | Now it should be equal to a number, in
this case 55, even though that's a string.
| | 03:11 | But it could be abc, it could be a word,
it could be some text, perhaps we're
| | 03:17 | asking the user for some input.
| | 03:19 | We hope they type a number, but what if
they don't? Well, step one is what I try
| | 03:23 | and do is I try and make a new variable,
in this case myNumber, and create that
| | 03:28 | by calling the function Number
and passing in this variable foo.
| | 03:33 | Now this function Number is built into
JavaScript the same way that alert is
| | 03:37 | built into JavaScript.
| | 03:38 | We pass it something and it will try and
convert it to a number and return that value.
| | 03:43 | Now if it can't convert it to a
number, let's say this was abc,
| | 03:48 | it will return "Not a Number."
| | 03:51 | But I need to know if that was the case.
| | 03:53 | I need to know if the
variable myNumber is not a number,
| | 03:57 | and luckily, we can check that.
| | 03:59 | We have another built-in function that
we can ask, which is isNaN, isNotaNumber.
| | 04:04 | Now again, it's the odd casing here.
| | 04:08 | Is is lowercase, uppercase N, lowercase a,
uppercase N. In this case, we pass in
| | 04:13 | the variable myNumber and the isNaN
function will return either true or false.
| | 04:18 | Now, be very careful about what it's doing here.
| | 04:21 | We're asking if it is not a number,
so it return true if it's not a number.
| | 04:26 | And we can write out the
message, "It's not a number!"
| | 04:29 | And what's often the case is you're
actually more interested in knowing that it
| | 04:33 | is a number, and we don't have
isNumber function, unfortunately.
| | 04:37 | Well, I could of course just write
an else statement after my if and then
| | 04:41 | process some code there, but if I want
to directly ask, what I'll do is phrase
| | 04:45 | this as kind of a double-negative here.
| | 04:47 | What I'm asking is if NOT NotaNumber
is true, and I'll do that by
| | 04:53 | calling isNaN function with the
exclamation mark in front of it.
| | 04:58 | So if isNaN returns false,
we'll use the exclamationmark to flip
| | 05:04 | that to true, and then we say
console.log( "It IS a number" ).
| | 05:07 | Yeah, you've got to love programming.
| | 05:08 | And finally, something that's coming
very handy with working with numbers is
| | 05:12 | something called the Math object in JavaScript.
| | 05:15 | This is an object that's just available
to you, has some very useful behavior,
| | 05:20 | some useful
functionality you can just tap into.
| | 05:22 | Well, how do we use it?
| | 05:23 | Well, let's just say we start off by
creating a variable called x that's equal
| | 05:27 | to 200.6, and I want to round that number.
| | 05:30 | What I can do is just type this code.
| | 05:32 | I'll create a new variable and set it
equal to Math, and we use the word Math
| | 05:36 | with an uppercase M, .round, passing in
the value x. And that's going to round it
| | 05:42 | to the nearest number.
In this case, it's going to be 201.
| | 05:44 | So what you'll see is a lot of Math. abilities.
| | 05:49 | We have things like Math.max, which we
can create multiple variables, pass in two
| | 05:55 | or three or four or five, and it
will just return the biggest one.
| | 05:59 | Flip side of that, Math.min.
| | 06:01 | And the Math object has a lot of these options.
| | 06:03 | We have Math.PI,
Math.random, Math.sqrt, Math.log.
| | 06:08 | Useful functionality and useful
behavior for working with numbers.
| | Collapse this transcript |
| Working with strings| 00:00 | So as we've seen, to create
variables that are string values, you simply
| | 00:04 | surround your word or your
phrase with double quotes.
| | 00:07 | Single quotes work as well.
| | 00:09 | What you can't do is mix them up,
can't have an opening single quote and a
| | 00:13 | closing double quote.
| | 00:14 | That can lead to issues if you need that
punctuation actually inside your string.
| | 00:18 | So for example, the phrase "Don't mix
your quotes inside single quotes" is not
| | 00:23 | going to work because the second
single quote there will be perceived as
| | 00:28 | closing the string.
| | 00:29 | We could of course put that inside the
double quotes because we're not now mixing them.
| | 00:34 | We're opening and closing the
string on the double quotes alone.
| | 00:37 | Problem can be if you want to
have both of them inside your string.
| | 00:42 | So in this case, the string itself should
contain both double quotes and single quotes.
| | 00:46 | If that's the case, what I have to do
here is I have to escape the double quotes
| | 00:51 | that I need to be used inside the string.
| | 00:53 | The way that I do that is just
surrounding them with a backslash and then
| | 00:57 | telling JavaScript these are not
intended to close the string, and they will be
| | 01:01 | considered just fine within the
wider opening and closing double quotes.
| | 01:06 | Now, strings can be treated as
objects, and what that means is they have
| | 01:10 | information we can ask of them.
| | 01:12 | They have properties that we can look at.
| | 01:13 | If I create a variable with this simple
phrase in it then I can use the name of
| | 01:18 | the variable, in this case phrase,
and a dot, and I can access the length
| | 01:23 | property, find out how long is the string?
| | 01:25 | How many characters is the string?
| | 01:27 | In this case, it's 24.
| | 01:29 | That's because, in a sense, strings
can be treated as arrays of characters,
| | 01:33 | and the same way we have a .length
property of an array, we have a .length
| | 01:37 | property of a string.
| | 01:38 | Well, not only do we have
properties, we also have methods.
| | 01:42 | We have things that these string
variables can do if we ask them.
| | 01:46 | So again, creating a variable called
phrase, I use that variable name phrase and
| | 01:50 | a dot, and I can call methods
like functions of the object.
| | 01:55 | So phrase.toUpperCase, which will
return, not surprisingly, the entire
| | 02:00 | string all uppercased.
| | 02:01 | I also have.toLowerCase.
| | 02:04 | We have methods like Split.
| | 02:05 | This will allow us to take a
longer phrase and pull it apart.
| | 02:10 | It will actually create
an array from our string.
| | 02:13 | So I use the variable named phrase.split,
pass it a parameter--I'll talk about
| | 02:18 | that in a second--and that will
return an array into the variable called
| | 02:22 | words, an array of words.
| | 02:24 | Now, what we're passing into the Split
method is a space, just using the double
| | 02:29 | quotes, space, double quotes.
| | 02:32 | That means I want to split this
string apart at the space, because it's
| | 02:38 | not always a space.
| | 02:39 | Say I have some comma-separated values.
| | 02:41 | I might call split and pass double quote,
comma, double quote, create an array
| | 02:47 | and split them apart on the commas.
| | 02:48 | So this creates us an array that is 5
elements long, 0, 1, 2, 3, and 4, and
| | 02:54 | notice that the last word, phrase,
also includes the period at the end of it.
| | 02:59 | But Split can be a very
useful method, as can indexOf.
| | 03:03 | This allows us to find out if a particular
term or word appears anywhere in the string.
| | 03:09 | So again, with a simple string variable,
I can call indexOf, passing in the term
| | 03:15 | that I'm looking for, which of course
has to be another string here, and it will
| | 03:18 | return the position of which that
string is found, if it's found it all.
| | 03:22 | So it's going to scan through the
original string, and in this case it'll say,
| | 03:26 | "Oh, I find the word 'groovy' appears
beginning at position 10," and it will
| | 03:32 | store that result in a new
variable called position.
| | 03:34 | If the term that you're searching for is
found right at the start, it'll return 0.
| | 03:38 | Now, the question is well, what
happens if that is not found at all?
| | 03:42 | Sometimes that's just as important, if
we need to know this term is not found.
| | 03:46 | Well, what that'll do is return -1.
| | 03:49 | So I could say put that in an if
statement, if phrase.indexOf, pass in DDDD
| | 03:56 | is equal to, again using the double
equals, which will be exactly the same as
| | 04:00 | triple equals here, -1, then we can do a
message saying, That word does not occur.
| | 04:06 | We called indexOf.
| | 04:07 | We passed in the term. It said -1.
| | 04:10 | It doesn't exist there.
| | 04:11 | Now, indexOf finds the first
occurrence of that term in the phrase.
| | 04:17 | If it could occur multiple times and we want
the last one, we can also ask for .lastIndexOf.
| | 04:23 | Next, the same way that we have Split
to split a string apart into an array, we
| | 04:29 | also have the method called Slice;
| | 04:31 | to allow us to slice out a
particular piece of that string.
| | 04:34 | So I am going to begin with a simple
phrase and I'm going to store that in a
| | 04:40 | variable called Phrase.
| | 04:42 | And what I can do is now call phrase.
slice, and pass in two numbers, in this
| | 04:48 | case 6,11, and that is the
starting position and the ending position.
| | 04:53 | So what this will do is count six
positions into that phrase variable, again,
| | 04:59 | treating the string as an array of
characters so we starting at position 0, and
| | 05:03 | it will grab from position 6, up to,
though not including position 11, because
| | 05:09 | we are grabbing five characters, from 6 to 11.
| | 05:12 | And it will return that value
into the new variable called segment.
| | 05:18 | Now although it might sound like it should,
slice does not change the original string.
| | 05:23 | So we have a copy of those letters,
but the first string remains unchanged.
| | 05:27 | Now there are actually a couple of
other methods in JavaScript that do very
| | 05:32 | similar things, such as .substring,
which in normal usage is basically
| | 05:37 | identical to slice, and .substr
that sounds very similar but the only
| | 05:42 | difference is that instead of taking
a start position and end position, it
| | 05:47 | takes a start position and a length.
| | 05:49 | Just the number of characters to return.
| | 05:51 | And you can use whichever
one makes most sense to you.
| | 05:55 | And finally, a couple of things to
be aware of with string comparison.
| | 05:58 | If we have two strings that are
exactly the same thing, then we can use the
| | 06:02 | double equals or the triple equals to
match them, but our string comparison here
| | 06:06 | is case sensitive, so right now if I
have Hello with an uppercase H and hello
| | 06:11 | with a lowercase h, they will not
be considered equal to each other.
| | 06:15 | If you're worried about that kind of
thing, the easiest thing would be to call
| | 06:18 | toLowerCase, or alternatively,
toUpperCase on both of them, if you were at all
| | 06:23 | unsure that there might be a casing
difference in there, and then I can check
| | 06:27 | them against each other.
| | 06:28 | Now something you might also be
concerned about is the sort order.
| | 06:31 | What happens if I use the
less than or greater than?
| | 06:34 | Let's say we start off with two strings:
| | 06:36 | aardvark and beluga.
| | 06:38 | If I want to ask, is String 1 less
than String 2, this works just fine.
| | 06:42 | It's going to compare beginning with
the first letters, and it's going to say
| | 06:45 | yes, A is less than B, so that will return true.
| | 06:48 | Well how about the case where I,
for example, use an uppercase B?
| | 06:53 | And I'm wondering is aardvark
less than Beluga with an uppercase B?
| | 06:57 | Well, in fact, this case will return false.
| | 07:01 | Now it might sound a little weird, but
because of the rules of sort order, all
| | 07:05 | the uppercase letters are considered
less than all the lowercase letters.
| | 07:10 | So in this case the lowercase a of
aardvark is considered to be greater than the
| | 07:15 | uppercase B of Beluga.
| | 07:17 | Again, something you could solve by
just converting both of them into either
| | 07:21 | lowercase or uppercase so that
case sensitivity is not an issue.
| | 07:24 | Now if you're brand new to strings,
I wouldn't at all expect you to be
| | 07:27 | remembering every single part of this.
| | 07:30 | The important thing of any
programming language is to figure out how do you
| | 07:33 | remember what those methods do
and what properties you have?
| | 07:36 | So just do be aware that you want to
have a good JavaScript reference guide, and
| | 07:41 | as good as any is actually the
reference guide that you'll find at
| | 07:44 | developer.mozilla.org, and these are
the guys that actually own the term
| | 07:49 | JavaScript, so they know
what they're doing here.
| | 07:51 | At this JavaScript Reference Guide what
you'll find is information about things
| | 07:56 | like arrays, about numbers, about
strings, about some of the other stuff we'll
| | 08:00 | cover later in the course.
| | 08:02 | And jumping into the string information,
you'll find information on getting the
| | 08:06 | length of the string, individual
characters, comparing strings, all the methods
| | 08:10 | that you might find are useful.
| | 08:12 | We couldn't really go through all
of them and wouldn't want to, here.
| | 08:15 | Having a reference guide bookmarked is
a very useful thing with JavaScript, as
| | 08:19 | with any programming language.
| | 08:21 | You don't want to try and
commit this all to memory.
| | 08:23 | You want to know where it is
and find it when you need it.
| | Collapse this transcript |
| Working with dates| 00:00 | Unlike many other programming
languages, JavaScript doesn't have a lot of
| | 00:04 | built-in objects for us to try and remember.
| | 00:07 | It has the Math object we can directly use.
| | 00:09 | It has an Array object.
| | 00:11 | One of the others is the Date object.
| | 00:13 | This is how we make a new date.
| | 00:15 | Now, while you could of course just
make several variables to hold a year,
| | 00:18 | month, and date yourself,
this one is a bit more useful.
| | 00:21 | So we use the var today--pick your own
variable name--equals the word new and
| | 00:26 | Date, with an uppercase D and using parentheses.
| | 00:29 | Now, if you don't pass any
parameters, you'll get it returned with the
| | 00:33 | current date and time.
| | 00:35 | Notice that, it's not just
the date; it's the time.
| | 00:37 | It's actually the time down to the millisecond.
| | 00:39 | Now, you don't always want a
date object that exists for today.
| | 00:43 | So you could create another one
which is a new Date and then passing in
| | 00:48 | year, month, and day.
| | 00:50 | But notice month is 0 based
like an array; it goes from 0 to 11.
| | 00:56 | The year is the real year, the day is the
real day 1 through 31, but month is 0 based here.
| | 01:01 | You can also get it down to, in this
case, seconds, year, month, day, hours,
| | 01:06 | minutes, seconds if you
want to be very specific.
| | 01:08 | Internally, a date object is stored as
the number of milliseconds since the 1st
| | 01:14 | of January 1970, which is a pretty common
way of doing it in the programming world.
| | 01:19 | Once you have a date object, like
having an array or like having a string, you
| | 01:23 | can do things with it.
| | 01:25 | We have a lot of methods of the date
object that begin with the word Get.
| | 01:30 | So after creating a new object, I can say
today.getMonth and it returns 0 through 11.
| | 01:37 | I can say today.getFullYear to
give me the four-digit version.
| | 01:42 | That one is not 0 based, so it
would return 2011, 2012, and so on.
| | 01:47 | There is actually a today.getYear,
but that one is officially deprecated,
| | 01:52 | meaning that it would work, but you're
not supposed to use it anymore.
| | 01:55 | The recommended one is getFullYear.
| | 01:58 | We have today.getDate.
| | 02:00 | Now, for those of you coming from
things like SQL, that might sound like
| | 02:04 | something that should return the full
date, but no. Here that will actually
| | 02:07 | return you the day of the month,
and it's 1 through 31, as opposed to
| | 02:12 | today.getDay, which would return 0 through 6
for the day of the week and 0 is the Sunday.
| | 02:21 | An example of using this is if I
define say a new Date, and here I'm doing a
| | 02:25 | date that is 1906, December because
we're 0 based for the month, and the 9th.
| | 02:30 | That's actually Grace
Hopper's birthday or Grandma COBOL.
| | 02:33 | So I'm going to then write out
console.log, give it a string, then a comma, and
| | 02:46 | then I will call myDate.getDay(),
opening and closing parentheses just to say
| | 02:53 | I'm passing no parameters there.
| | 02:55 | I then close the parentheses of
the console.log call and finish the
| | 02:59 | statement, rerun that.
| | 03:01 | Apparently, Grace Hopper was born on a
Sunday, and simple silly example there,
| | 03:06 | but that's how you start to get into
the deeper parts of the Date object.
| | 03:11 | We even have today.getHours.
| | 03:14 | This one is also 0 based,
0 through 23, and there's today.getTime.
| | 03:18 | Now, this one will actually return the
milliseconds since the 1st of January 1970.
| | 03:24 | Now, that sounds like it's a little bit
esoteric, but in fact getTime is one of
| | 03:28 | the most useful methods of the Date
object, and you'll probably see it used
| | 03:33 | quite a lot, because it's a very
direct way to figure out, is something less
| | 03:38 | than something else?
| | 03:40 | If one date is less than other one,
| | 03:42 | I don't have to bother comparing years
and months and days, if I can just get
| | 03:47 | the big number that represents the milliseconds.
| | 03:50 | Now conversely, we have all these Get methods.
| | 03:53 | We also have Set methods.
| | 03:55 | So where we have getMonth, we also
have setMonth where we can pass in the
| | 03:59 | number of the month,
| | 04:00 | set for year, setDay to manipulate those dates.
| | 04:04 | Again, you can find the full
description of these in any online
| | 04:08 | JavaScript reference.
| | 04:09 | One thing we'll often have to do is
compare dates, and this does not work the
| | 04:13 | way most people think it does.
| | 04:15 | Let's say I create two new date objects.
| | 04:18 | I'm setting them both here to the
1st of January and the year 2000.
| | 04:22 | Again, we're passing a 0 for the month,
because the month is 0 based here, and
| | 04:25 | then I ask, is date1 equal to date2?
| | 04:29 | And I'm using the double equals here.
| | 04:31 | Now, this would actually respond as false.
| | 04:34 | Now, as whether I use double equals or
triple equals, that's not the problem here.
| | 04:38 | The problem is is the dates are
object, and they're a bit more complex.
| | 04:42 | What JavaScript is doing is looking at
and going, are these the same object?
| | 04:46 | Well, no, they're actually not.
| | 04:48 | They may internally have the same values as
we're concerned, but it's not going that deep.
| | 04:53 | It's realizing there are two
different objects and saying this is false.
| | 04:56 | We need a simpler way to compare
them, the way that we can compare say
| | 05:00 | numbers, which is very easy.
| | 05:02 | So what I'll do instead is
I'll ask if date1.getTime--
| | 05:06 | that's that really useful method that just
returns milliseconds--is equal to date2.getTime.
| | 05:12 | Now, calling both of these are
just going to return milliseconds.
| | 05:16 | It would be like comparing two
numbers, and this would return true.
| | 05:20 | Now you can also use this very easily
with comparisons such as greater than, less
| | 05:25 | than, greater than or equal
to, less than or equal to.
| | 05:28 | So this is one of those areas where the
methods of the Date object come in very
| | 05:31 | handy indeed if you don't want to have
to manually start comparing year parts
| | 05:36 | and month parts and day parts.
| | Collapse this transcript |
| Working with objects| 00:00 | So JavaScript does have this idea of
objects, although if you're used to formal
| | 00:05 | object-oriented programming
languages, you'll find it very basic.
| | 00:08 | It has a few very straightforward
ideas about what makes an object, and we've
| | 00:12 | already been doing it.
| | 00:13 | If we make an array, that's an object.
| | 00:15 | If we make a date, that's an object.
| | 00:18 | These objects are self-contained pieces.
| | 00:20 | If I have an array, I can use the
dot operator to say I'm interested in
| | 00:24 | its .length. In this case it would be 5.
| | 00:27 | If I have a date, I can call methods of it.
| | 00:29 | Again, these are functions
that belong to an object.
| | 00:32 | So I can say getTime or getFullYear,
and as soon as we start touching our
| | 00:37 | web pages, we'll have other objects
that represent all the different pieces
| | 00:41 | of the page, what's referred to as
the DOM or Document Object Model, and we
| | 00:47 | can even make our own.
| | 00:48 | So we're going to get
comfortable working with objects.
| | 00:51 | And at its core, the idea of
an object is really simple.
| | 00:55 | It's just a container that gathers
together some data and some behavior.
| | 00:59 | So we know how to make variables.
| | 01:01 | We know how to make functions.
| | 01:03 | An object just allows us to gather
variables and functions that belong together
| | 01:07 | and give them a name.
| | 01:08 | So let's say here I'm
making some regular variables:
| | 01:11 | playerName, playerScore, playerRank.
| | 01:13 | It's just creating those three in memory.
| | 01:17 | And I realize that really these belong together.
| | 01:20 | It would be nice if I could
enclose them in a larger object.
| | 01:23 | Now, I could do this in an array, but I
don't really want to have to worry about
| | 01:27 | the 0, 1, 2 whole idea.
| | 01:30 | So what I'll do instead is I'll run this line.
| | 01:34 | First off, I'll say var player--again, I'm
still creating a variable--equals new Object.
| | 01:40 | This creates me a generic
object container and calls it player.
| | 01:45 | What I then do is just decide, what do I
want the internal pieces of this object to be?
| | 01:51 | So in this case, player.name = "Fred",
player.score = 10000, player.rank = 1.
| | 01:58 | So when we do this our
data is now one level deeper.
| | 02:03 | It's inside this player object.
| | 02:05 | So we use what's called dot syntax
to say this object dot this variable.
| | 02:10 | Although officially speaking, when they're
outside an object we call them variablesm
| | 02:14 | when they're inside an
object we call them properties.
| | 02:18 | A property is really just a
variable that belongs to an object.
| | 02:21 | Now, because it's quite useful to do
this, the same way that there is shorthand
| | 02:25 | for creating arrays, there is also
a shorthand for creating an object.
| | 02:29 | I create a new variable--
| | 02:30 | I'll call it player1--
and I use the curly braces.
| | 02:33 | Now, here I'm not using them to surround a
if statement code block or in a while loop.
| | 02:38 | This is a shorthand for creating an object.
| | 02:41 | And then inside the curly braces I use
this name value pair, in this case three
| | 02:47 | sets of information: name: "Fred,"
score: 10000, rank: 1
| | 02:54 | and it creates the object
and those properties inside it.
| | 02:59 | And then I could just do another line
of code and create player2, use the same
| | 03:03 | format, but create a different
object with different properties.
| | 03:07 | And in this fashion I could get to
player1.name, I could get to player2.name,
| | 03:10 | player3.name, and so on.
| | 03:12 | So if we create a couple of objects, it's
very easy to then write out information
| | 03:17 | about each individual object.
| | 03:19 | In this case, we'll write out
console.log(player1.name).
| | 03:23 | That reaches inside the
object and writes out Fred.
| | 03:26 | But it'd be nice to do a bit more to this.
| | 03:28 | What I'd also like to do is associate
some behavior with these objects, not just
| | 03:33 | some data, not just some
information, but what can player1 do?
| | 03:36 | What can player2 do?
| | 03:37 | What would be nice is if we could create
a function called say playerDetails and
| | 03:43 | that one I'll just put a comment inside
this right now that this should display
| | 03:47 | information about each player.
| | 03:50 | Now sure, what I could do is just
define this function independently and
| | 03:54 | declare it as accepting a parameter,
but I'm not going to do it that way.
| | 03:58 | What I'd like to do is make this
function part of these two objects.
| | 04:03 | And the way I need to do that is to
associate it with the objects themselves.
| | 04:07 | What I'm really doing here is
making this a method of my objects.
| | 04:11 | So what I'd like to be able to
say is say player1.showDetails or
| | 04:15 | player1.logDetails and have it
call this function. I am associating this
| | 04:20 | function with this object.
| | 04:21 | And it's completely up to
me how I want to do this.
| | 04:24 | I'm going to say player1.logDetails.
| | 04:27 | You might think, well,
where that this come from?
| | 04:29 | I'm just making it up right now, and I'm
setting it equal to playerDetails, which
| | 04:33 | is the name of the function.
| | 04:35 | I'm not calling it here.
| | 04:37 | I'm not calling that function at all.
| | 04:39 | I'm just associating it with my player1 object.
| | 04:42 | And similarly, what I want to do is
exactly the same thing with the player2 object.
| | 04:48 | So what does this do?
| | 04:49 | Well, now both of these objects actually
have a method called logDetails, and if
| | 04:55 | we call it, it will just reach
through and call the playerDetails function.
| | 04:59 | Okay, so what. What will it do?
| | 05:01 | Well, I'd like to actually, let's
just do a console.log message here,
| | 05:06 | information about the player.
| | 05:08 | If I think, well, I want to write out
the name of the object, but I don't know
| | 05:12 | whether I'm going to be doing
player1.name or player2.name.
| | 05:17 | I just want to do one at a time,
and I could call this for either.
| | 05:20 | Well, here's the thing that we do.
| | 05:22 | If I know this function is going to be
associated with different objects, what I
| | 05:27 | can use is the word this
to refer to the current one.
| | 05:32 | So whatever object it is, I'm going to
go into its name property, or its score
| | 05:36 | property, or its rank property.
| | 05:38 | So I'll put together a bit more of a
message, this.name and a little string has
| | 05:43 | a rank of, and then we use the
concatenation and just to make it clear I'll
| | 05:49 | split it across a few lines, this.rank.
| | 05:58 | Close the console.log
parentheses, close the semicolon.
| | 06:01 | Now, right now if I ran this code,
nothing would actually happen, because I've
| | 06:06 | defined the function, I'm creating
the objects, but we don't have any
| | 06:08 | information coming out.
| | 06:10 | What I can do sometime later in the code
is finally call the logDetails function
| | 06:16 | of player1 and the
logDetails function of player2.
| | 06:19 | And we're going to use the
parentheses to let JavaScript know, yes, we're
| | 06:22 | actually calling it now.
| | 06:23 | So I'm going to go ahead and run this, and we
get the message out here, Fred has a rank of
| | 06:29 | 1 and a score of 10000.
| | 06:31 | Because it's calling it on Fred,
it's jumping and saying, "What does
| | 06:34 | this logDetails do?"
| | 06:35 | Oh, well, it calls playerDetails,
and that's this function here, which for the
| | 06:40 | current object, this.name is Fred,
this.rank is 1, this.score is 10000.
| | 06:46 | And I could just call that for the
second object, and then we get the second
| | 06:55 | message out, which is that object's information.
| | 06:58 | For those of you coming from more
formal object-oriented languages, you're
| | 07:01 | almost certainly recognizing that
JavaScript seems very casual about this.
| | 07:05 | There's not a lot of rules being enforced here.
| | 07:08 | And yes, that's true. We can just kind of go ahead
and make these objects and tie functions to them.
| | 07:13 | It all seems quite loose and flexible.
| | 07:15 | Well, that's JavaScript for you.
| | 07:17 | And know that JavaScript doesn't have
formal classes as other object-oriented
| | 07:22 | languages do, but you can emulate the
same effect using a normal function and
| | 07:26 | something called a prototype,
but that's not necessary for us right now.
| | 07:29 | So I'm going to leave it until later on
in the course. Because most people most
| | 07:34 | of the time don't need to get really
deep into object orientation, this will be
| | 07:38 | more than enough to get us started.
| | 07:40 | Because knowing this, knowing that the
idea of objects, the idea of properties,
| | 07:45 | the idea of methods, allows us to
move on and start working with the really
| | 07:50 | important objects in JavaScript, the
window object and particularly the document
| | 07:55 | object, the most important
object for any JavaScript developer.
| | Collapse this transcript |
|
|
4. Understanding the Document Object ModelWhat is the DOM?| 00:00 | So we've been focused completely on the
JavaScript language for these past few
| | 00:04 | movies, and that is a great
way to start with JavaScript.
| | 00:07 | But of course it doesn't run in a vacuum.
| | 00:10 | Our scripts will be attached to a web
page, and it's the web page that comes first.
| | 00:15 | They bring our script with
them, not the other way around.
| | 00:18 | So our page, whether a simple page or a
complex one, is the canvas that we're painting on.
| | 00:23 | It's the environment we're affecting.
| | 00:25 | It is the world that we live in. And we
must be able to reach from a JavaScript
| | 00:29 | into these pages and cause these
pages to reach back into our script.
| | 00:33 | We do that by understanding the
DOM, the Document Object Model.
| | 00:39 | I consider knowing your way around the
DOM to be the single most important skill
| | 00:44 | for a JavaScript programmer to develop.
| | 00:46 | But this is a term that's often a
little tough to understand the first time you
| | 00:49 | hear it, because it's kind of vague.
| | 00:52 | People ask well, what is the DOM?
| | 00:53 | Is it a language, is it part
of JavaScript? What is it?
| | 00:57 | Then you look it up on the web,
and you find phrases like, "The Document Object
| | 01:00 | Model is an application programming
interface that defines logical structure of
| | 01:03 | well-formed an XML and HTML documents,"
and it really doesn't help most people,
| | 01:07 | but it's quite a simple idea at heart.
| | 01:10 | So let's take the DOM piece by piece.
| | 01:13 | Well, what do I mean by document?
| | 01:15 | Well, if I am in Microsoft Word,
that might mean one thing, but we're not.
| | 01:20 | For us, the document simply means the
page, not the site, the web page; the web
| | 01:25 | page is the document.
| | 01:27 | But this document can be
represented in different ways.
| | 01:30 | Well, it already is.
| | 01:31 | You know this already.
| | 01:32 | After all, which one of these is the web page?
| | 01:36 | Well, both of them.
| | 01:37 | One is the browser view, one is the source code.
| | 01:40 | It's the same document;
it can have a different representation.
| | 01:43 | What we need to also understand is how
JavaScript perceives the same document,
| | 01:48 | same document, different representation.
| | 01:51 | But if that's all we mean by document,
then what's the object part of the
| | 01:55 | Document Object Model?
| | 01:56 | Well, when we talk about objects in
programming languages, it's really easy to
| | 02:00 | get wound up in deep semantic
meaning, but we don't need to.
| | 02:03 | We've already used objects in JavaScript.
| | 02:06 | Dates are objects, arrays are objects.
| | 02:08 | We've made our own objects.
| | 02:10 | An object is just a thing, some thing,
any thing that makes sense to treat as an
| | 02:16 | individual piece, even if
it contains other things.
| | 02:19 | For us, it really means the elements, the
components, the individual pieces of this document.
| | 02:24 | If I talk to a user, I can say, "Look at
the headline, look at the bullet point
| | 02:28 | list, look at the whole page, even look
at the third letter in the second word,"
| | 02:32 | and they understand what I mean.
| | 02:34 | If I talk to you as a web developer, I
can say, "Now, look at the h1 tag, look at
| | 02:40 | the unordered list part,
look at the whole document."
| | 02:43 | All of these things are objects and yes,
sometimes they contain other objects. That's okay.
| | 02:49 | You have no problem understanding the
unordered list piece contains individual
| | 02:54 | list item pieces, and in the same way,
what we'll do is we'll have a JavaScript
| | 02:58 | term for every piece, for every object
at whatever level that makes sense, from
| | 03:03 | the entire document to the smallest
piece, and that leads us to the idea of the
| | 03:09 | model of Document Object Model.
| | 03:11 | Now, what they mean here is model
as in a business model or data model.
| | 03:15 | You've seen flowcharts or database
diagrams, the idea of taking something
| | 03:18 | complex and making it
abstract, making it simple.
| | 03:21 | But with a web page, we should be able
to take any HTML and represent it as a
| | 03:27 | tree structure. With the simplest of
HTML here, it contains a head and a body.
| | 03:33 | The head itself contains the title
element, the body contains an h1 for a
| | 03:38 | heading, a p for a
paragraph, and an unordered list.
| | 03:41 | The unordered list contains three list items.
| | 03:44 | We're able with this diagram to
represent the structure, the tree structure
| | 03:49 | of this HTML document.
| | 03:51 | We could even decide on words for these.
| | 03:53 | If we were drawing this up on a whiteboard,
we could call each of these pieces nodes.
| | 03:58 | We'll pick a p or a body or
h1 and call them all nodes.
| | 04:01 | We could even develop terms to
describe relationships, like picking a node and
| | 04:05 | asking, what's its parent?
| | 04:07 | Does it have any child nodes?
| | 04:09 | And really. here what the model means is,
what do we call these things, and how
| | 04:13 | do we describe the relationships between them?
| | 04:16 | Because it's not going to do me any good
if I make up my own names for these objects
| | 04:19 | that conflict with your names for these objects,
| | 04:22 | if I call a piece a node
and you call it a doohickey.
| | 04:25 | So the model is simply a set of
terms that we can agree on, a set of
| | 04:30 | standards that we can use.
| | 04:33 | So what we end up with is an
agreed-upon set of terms that describe exactly how
| | 04:38 | to interact with the pieces of a web page.
| | 04:40 | That's a long phrase, so we
call it the Document Object Model.
| | 04:46 | It's not a language. It's an idea.
| | 04:49 | It's a convention. But JavaScript agrees on
this DOM, so it's available in JavaScript.
| | 04:55 | It's an agreed-upon terminology that
will let us describe and interact with any
| | 04:59 | web page. Not one specific one, any one.
| | 05:03 | When I know the basic concepts of
the DOM, I can write JavaScript that
| | 05:07 | navigates around any page.
| | 05:09 | I can say I want to get the text of the title.
| | 05:11 | I want to get the second paragraph element.
| | 05:14 | I want to get the third link in the
menu and change how it's displaying, in
| | 05:18 | this case hide it, or change the
background color of all paragraphs, or get all
| | 05:22 | the list item elements, or find an image
and start to move it, change a link from
| | 05:27 | its default behavior to actually
performing a JavaScript function, or even
| | 05:31 | creating new unordered lists,
or creating paragraphs, or creating menus and
| | 05:35 | inserting them into the page on
the fly, and a lot more besides.
| | 05:41 | That's why we need to know the DOM.
| | 05:43 | It is the way to reach into the page
from our script and the way our page can
| | 05:47 | reach into our script.
| | Collapse this transcript |
| Working with nodes and elements| 00:00 | So we might think about our web page
content one way, but the DOM thinks about
| | 00:05 | it in terms of nodes.
| | 00:07 | Every web page we have,
every document is made of nodes.
| | 00:11 | However, it goes a little deeper than
just this basic example I am showing here
| | 00:16 | of one node per tag, because as
we know, our HTML does have tags.
| | 00:21 | Sure, it has got the body tag, it has
got p tag, header tags, and so on, but we
| | 00:26 | also have blocks of text.
| | 00:28 | We have attributes, sometimes one
attribute, sometimes several attributes
| | 00:33 | as part of an element.
| | 00:35 | We can have comments and so on,
and these are all regarded as different kinds of
| | 00:40 | nodes in the DOM, and the reason for
this is so we can get to them directly too.
| | 00:45 | If I want to, I can ask, what is
the text for the second paragraph?
| | 00:49 | What's the source attribute of an image tag?
| | 00:52 | So really, our diagram is a little bigger.
| | 00:55 | If I had to display every single node
here, I'd end up with quite a lot, because
| | 01:00 | we have nodes that represent elements,
attributes, texts, comments, and so on.
| | 01:06 | And officially, if you look at the
DOM documentation, there are actually 12
| | 01:11 | node types in the DOM.
| | 01:13 | But really, we're only
interested in three of them:
| | 01:17 | elements, attributes, and text.
| | 01:20 | And here's an example.
| | 01:21 | Let's say we have just a simple
snippet of HTML here, an unordered list.
| | 01:27 | It has got an id of optionList.
| | 01:29 | It has got a three list items inside it.
| | 01:31 | Well, the whole unordered list
element from the top to the bottom is
| | 01:36 | considered one node, an element node,
but inside that it has another node that
| | 01:42 | represents the attribute of
id = "optionList", so it's a different kind of
| | 01:46 | node, an attribute node.
| | 01:48 | But as we start to look deeper inside it,
we realize that we've got three list
| | 01:53 | item nodes. Those are also element nodes.
| | 01:56 | And not only that, because the text
in any element is actually considered a
| | 02:01 | separate node, each of these li
elements has a text node attached to it to
| | 02:07 | describe the text inside them.
| | 02:09 | So as far as the DOM is concerned, we
can drill into any very specific piece,
| | 02:15 | even of this simplest little piece of HTML.
| | 02:18 | Now, the idea that the text node is
actually separate from the element might
| | 02:23 | sound nitpicking, but it leads to
quite a common mistake, that when you have
| | 02:26 | element nodes such as paragraphs, or
list items, or H1 tags, they do not
| | 02:33 | directly contain that text.
| | 02:35 | Officially speaking, according to
the DOM, you have this text node that
| | 02:39 | contains the text of a paragraph, or a
text node that contains the text of a list
| | 02:44 | item or of a heading.
| | 02:46 | But having said that, we're typically
interested in grabbing the element nodes first.
| | 02:51 | That's the way most web
developers think about an HTML page.
| | 02:56 | It's made of elements, the tags that we
have, our paragraphs, our anchor tags,
| | 03:01 | our unordered lists, our headings.
| | 03:03 | And the great thing is, once we have
got any of those nodes, it's easy to work
| | 03:07 | our way up and down the tree to get
to any text node that might be below it.
| | 03:10 | And luckily, it's not hard to do.
| | 03:12 | So next up we're going to write the
code to grab one of these element nodes.
| | Collapse this transcript |
|
|
5. Working with the Document Object ModelAccessing DOM elements| 00:00 | So how do we write JavaScript to
grab hold of one of these nodes?
| | 00:04 | And well, it really depends.
| | 00:06 | The main question you
have to ask is, is it unique?
| | 00:10 | The thing that you're after, is it unique in
the document, and that means does it have an ID?
| | 00:16 | If I'm after, say, an unordered list,
I need to ask the question, does it
| | 00:20 | have an ID in the HTML?
| | 00:22 | You know that you can add the ID and
class attributes to any of your HTML
| | 00:27 | elements, but that a class can be added
to multiple elements, but an ID should
| | 00:32 | only be applied to one. It should be unique.
| | 00:35 | And if the element that you're after
has that unique ID, you can grab it in
| | 00:39 | JavaScript by using possibly the
most important method of the document
| | 00:43 | object, which is this one,
| | 00:46 | document.getElementById, and you
pass in the ID of that HTML element.
| | 00:54 | Now notice the uppercase
and lowercase mixture here.
| | 00:56 | It is, of course, case sensitive.
| | 00:59 | So document is lowercase,
then a dot, then getElementById.
| | 01:03 | get is lowercased. Every
subsequent word begins with uppercase.
| | 01:07 | Element, By, and Id, but Id is not
uppercase D, which often messes people up there.
| | 01:13 | So what does this do? Well, we're going
to call it, but not just like this.
| | 01:17 | What we're going to do is create a
variable and set it to the result of calling that.
| | 01:24 | So if I want to grab hold of this
unordered list that has an id of abc, I'm
| | 01:29 | going to create a new variable
called myElement and set it equal to
| | 01:33 | document.getElementByID and
pass in abc, the ID of the element.
| | 01:38 | And what we're doing here is we're
creating a variable that is really a handle
| | 01:44 | to that place in the DOM.
| | 01:46 | We can then use that variable, in this
case I've called it myElement, to read
| | 01:50 | properties of the element.
| | 01:52 | You can call methods of the element.
| | 01:53 | You can even change that element.
| | 01:55 | Now it's important to understand that
when I do this getElementById, I'm not
| | 02:00 | just making this detached
copy of this single piece.
| | 02:03 | Now I have a handle right into this document.
| | 02:06 | I can use it to go down to the child nodes.
| | 02:10 | I can use it to go up to the parent node.
| | 02:12 | It's not the detached copy of the one element;
| | 02:15 | it's more like a pathway into
this particular place in the DOM.
| | 02:18 | Well, what if I don't have an ID on the
element that I'm after, or what if I want
| | 02:24 | more than one element?
| | 02:25 | Well, then we have the
getElementById's close relative, document.getElementsByTagName.
| | 02:32 | Now notice, not getElement,
but getElements, plural.
| | 02:36 | What this is going to do is go through
our document and give us back any of the
| | 02:42 | element nodes that are anchor
elements, a tags in your HTML.
| | 02:46 | Well, how does that work?
| | 02:48 | So let's say we go back to the
same ID of the simplified DOM here.
| | 02:52 | I'm going to create a new variable
called myListItems and set it equal to
| | 02:56 | document.getElementsByTagName, passing
in li, which means, find me all the nodes
| | 03:03 | that are list item elements and return those.
| | 03:05 | Well, how does it store that in
one variable? It makes an array.
| | 03:10 | So it makes an array called myListItems,
| | 03:13 | it finds all the list items in the
entire document, and then in each position of
| | 03:18 | the array, in this case,
there's three positions to it,
| | 03:21 | we'll have a handle to that
particular place in the DOM.
| | 03:24 | So we could just use the square qrackets
and say myListItems(0) or myListItems(1)
| | 03:30 | or myListItems(2).
| | 03:30 | Now if you call the same method,
getElementsByTagName and pass in a tag name
| | 03:36 | that doesn't exist, so in my simplified model
here I don't actually have any a href elements,
| | 03:42 | what will happen is it will still
return array, but the array will be empty.
| | 03:47 | It won't even have a length of 1.
| | 03:49 | It will have a length of 0.
| | 03:50 | There's nothing there.
| | 03:53 | So in this folder that I'm looking at
here, I have a web page and some attached
| | 03:57 | CSS and image just to give us something
a bit more interesting to look at and to
| | 04:02 | have a bit of content to work with.
| | 04:04 | If I were to look at the page
source of this, there's nothing
| | 04:09 | particularly remarkable.
| | 04:10 | It's standard HTML, although down
towards the bottom, I do have a link to a file
| | 04:15 | called script.js just
before the closing body tag.
| | 04:18 | And right now there is nothing in script.js.
| | 04:24 | I'm going to open that up in Aptana,
though I could open up in any editor.
| | 04:34 | And just to have something else to look
at, I'm going to flip over and just open
| | 04:37 | up this HTML file in the same editor.
| | 04:40 | I'm not intending to change the HTML here;
| | 04:42 | I just want to be able to
flip back and forth to it.
| | 04:51 | So I can see by scanning my HTML that
I actually have quite a lot of elements
| | 04:55 | that have an ID to them.
| | 04:58 | And the main reason this has been done
is so they can be styled with CSS, but it is
| | 05:03 | very handy for us as
JavaScript programmers as well.
| | 05:06 | I can see, for example, I have an
anchor tag here with an ID of mainTitle.
| | 05:12 | I'm going to write some
code to grab hold of that.
| | 05:14 | So let's create a new variable.
| | 05:16 | I'll call it mainTitle.
| | 05:28 | Again, we must take care to make sure
that the casing that we're using to grab
| | 05:32 | it is exactly the same as
it is in the HTML itself.
| | 05:36 | The variable I didn't
have to call the same name.
| | 05:39 | I can call that whatever I want.
| | 05:40 | And the question is, now what?
| | 05:42 | Well, I have this variable which
represents the object, the element object, and
| | 05:48 | like all objects, like dates,
like arrays, like even strings,
| | 05:51 | we have things that we can ask for them.
| | 05:53 | So I'm going to write
out a few console messages.
| | 06:04 | And with console.log we can put a
string, then a comma, and then some
| | 06:07 | interesting information.
| | 06:08 | So I'm going to say the message "This is
an element of type" and I'm typing in my
| | 06:16 | variable name, .nodeType.
| | 06:18 | If you have an editor that pops up
some of the auto-completion stuff, then
| | 06:22 | great; otherwise, just type it in anyway.
| | 06:24 | nodeType will be a property we can
access as soon as I have something back
| | 06:30 | from getElementById.
| | 06:33 | If you recall, I said there were
three kinds of nodes we were interested in:
| | 06:37 | elements, attributes, and text.
| | 06:40 | Internally, they should have the nodeTypes 1,
2, and 3, so this should write us back out 1.
| | 06:47 | I'll do another one here, console.log.
Writing out another property called
| | 07:04 | innerHTML, and as always, paying
attention to the case sensitivity of this.
| | 07:19 | And the last message I'm going to write
out is a message that will tell me how
| | 07:22 | many child nodes I have, because when we
grab hold of this element, we don't just
| | 07:28 | have the element by itself;
| | 07:29 | we'll also be bringing along references
to any child nodes it has, or if I want
| | 07:34 | to look up the way, any parent nodes as well.
| | 07:36 | So every node has a childNodes property that
might be empty, but I don't think it is here.
| | 07:41 | It's actually an array, so it
itself will have a length property.
| | 07:45 | I'm just going to hit Command+S or
Ctrl+S to save this, flip back over into
| | 07:51 | Firefox where I actually do still
have this running, and refresh the page.
| | 07:55 | Now I'm doing console messages, so I need to
have Firebug opened to actually see the console.
| | 08:05 | Refresh that page, and we
get "This is an element of type:
| | 08:09 | 1." The Inner HTML is apparently
Welcome to Explore California!
| | 08:16 | and this particular node has one child node.
| | 08:19 | So we're programmatically reaching
into the HTML here, grabbing this content,
| | 08:25 | and finding information about it.
| | 08:26 | This is the innerHTML path
that I was actually pulling out.
| | 08:29 | I'm going to jump back in and
do a little bit more code here.
| | 08:34 | Now, let's use the document.getElementsByTagName.
| | 08:37 | What I'm going to do here is create a
new variable on Line 7 called myLinks,
| | 08:41 | this will be an array, and tell this to
fill it with as many anchor tags as I have.
| | 08:46 | Then I'm going to write out a log
message that just says myLinks.length.
| | 08:51 | I'm just going to save that; for
me Command+S or Ctrl+S, depending on
| | 08:55 | what platform you're on.
| | 08:56 | Back over into Firefox, refresh the page,
and then apparently we have 19 links,
| | 09:03 | 19 anchor tags on this page, and we're
getting all those elements by tag name.
| | 09:08 | Yes, I'm not doing much with them yet,
but you can see how we can start to drill
| | 09:12 | down into the properties and
the information about that data.
| | 09:17 | So documents.getElementById and
getElementsByTagName. Very, very powerful, hugely useful,
| | 09:24 | probably one of the most
often used things in all of JavaScript.
| | 09:28 | And they're actually a little bit more
powerful than this because even though most
| | 09:32 | people think of this method as
document.getElementById, it's more flexible than that.
| | 09:38 | As soon as I have, say, an element node,
I can use the same method at any level
| | 09:44 | in the DOM, not just the top-level document.
| | 09:47 | What does that mean?
| | 09:48 | Let's say, for example, I have a
slightly more complex DOM here and I run a line
| | 09:56 | of code here that says getElementsByTagName.
| | 09:58 | So it's document.getElementsByTagName("li").
| | 10:02 | Give me all the list items back.
| | 10:04 | If I can just run this, what I'll do is
I'll grab all the list items from every
| | 10:09 | level of the document.
| | 10:10 | But let's say that's not what I was after.
| | 10:13 | What I can do is kind of a two-stage thing here.
| | 10:16 | First, I would use document.getElementById
to grab that unordered list with an
| | 10:23 | ID of abc, and that gives me a
new variable called myFirstList.
| | 10:27 | Then I'm going to call
getElementsByTagName again, but instead of using the
| | 10:32 | document to call it, I'm going to
say myFirstList.getElementsByTagName.
| | 10:38 | And what that means is it'll start at
the unordered list position and look
| | 10:43 | downwards and only give
me back those list items.
| | 10:46 | So I'm using another element,
and you'll find this all the way up and down the
| | 10:52 | DOM, that you're able to reuse the same method.
| | 10:55 | Once you start to get to grips with
the properties that are available and the
| | 10:58 | methods that are available, you can
pretty much get anywhere you want.
| | Collapse this transcript |
| Changing DOM elements| 00:00 | Using JavaScript to read information
about the nodes on our page is all very
| | 00:04 | well, but we really want
to be able to change it.
| | 00:07 | Step one for doing this is
always going to be get the element.
| | 00:11 | You need that variable to
be a handle on the element.
| | 00:15 | Sure, we know that we've got elements,
and we also have attributes and text
| | 00:19 | nodes, but it's the element that comes first.
| | 00:22 | Attribute nodes and text
nodes belong to elements.
| | 00:25 | If you're writing HTML, you
don't write an attribute by itself.
| | 00:29 | It's the attribute of an element.
| | 00:31 | So that's what comes first.
| | 00:32 | Step two is okay, then we can change it.
| | 00:36 | The question is, what do
you want to change about it?
| | 00:38 | If you were manually editing this code in
a text editor, what would you want to do?
| | 00:43 | Do you want to pick an attribute
and change it or add a new attribute?
| | 00:47 | Do you want to change a link inside a heading?
| | 00:50 | Do you want to add a whole bunch of new
elements inside a div or inside a list?
| | 00:55 | Well, we can do all of that, but let's
talk about changing existing elements,
| | 00:59 | rather than creating new ones.
| | 01:01 | We'll get to that in a minute.
| | 01:02 | One of the simplest changes we could make
is to change an attribute of an element.
| | 01:07 | Now once we've got that element,
JavaScript actually has two methods we can use
| | 01:11 | to directly work with its attributes:
| | 01:14 | there's getAttribute and setAttribute.
| | 01:17 | getAttribute is very simple.
| | 01:18 | We just need to say what attribute.
| | 01:21 | You pass this as a string in double quotes.
| | 01:24 | It's the name of the attribute:
align, title, class, source.
| | 01:30 | setAttribute very similar,
but we need a bit more information.
| | 01:34 | We pass in a value.
| | 01:36 | So we call the setAttribute method.
| | 01:38 | We pass it the name in quotes.
| | 01:39 | We pass it the value in
quotes, always as a string.
| | 01:42 | If the attribute doesn't
currently exist, it will be created.
| | 01:46 | Let's take a look at this.
| | 01:48 | So I have a simple HTML page that I have here.
| | 01:51 | There's nothing remarkable about it.
| | 01:53 | It's just to have something to work with.
| | 01:54 | You could work with a test page yourself.
| | 01:57 | I have that open in my editor here,
and down at the bottom, I have a link to my
| | 02:02 | script.js file, which is in the same
folder, which is actually over here.
| | 02:08 | It has a few lines, but they're all
commented out, just so you don't have to
| | 02:11 | watch me type code all the time.
| | 02:12 | So what I'm going to do is I want to grab
hold of a section of this page and change it.
| | 02:18 | The thing I'm going to grab is
actually this div here on Line 22.
| | 02:22 | It's got an ID of mainContent.
| | 02:25 | It doesn't currently have any
attributes set, but we can change that.
| | 02:30 | So over in my JavaScript I am
just going to uncomment Line 1 here.
| | 02:33 | It's just a document.getElementByID
of mainContent storing it in a
| | 02:38 | variable called mainContent.
| | 02:39 | Then I can use that variable,
and just call setAttribute.
| | 02:44 | The attribute is align, and the value is right.
| | 02:47 | So I'll just save that JavaScript file,
flick over into Firefox, and this is the
| | 02:53 | area that I should be affecting.
| | 02:55 | That's what that div is containing.
| | 02:57 | So if I refresh this page, yes
indeed, we've got align right now.
| | 03:01 | So it's a very easy task to just
change the attributes of an element that
| | 03:06 | you have a handle to.
| | 03:07 | Well, what if we want to get
a little bit deeper than that?
| | 03:10 | What if I want to change
the contents of an element?
| | 03:14 | Say I've got an h1 that I want to
change or a paragraph that I want to change.
| | 03:18 | Well, you have a couple of options here.
| | 03:21 | The simplest option is a method called
innerHTML, and that's inner in lowercase,
| | 03:26 | and HTML in uppercase.
| | 03:28 | You can use that on any element you have.
| | 03:30 | It allows you to either read or
change the entire contents of that element.
| | 03:34 | So let's say here I've got an
anchor tag with an ID of mainTitle.
| | 03:41 | Right now, it contains the
words "Welcome to Explore California!"
| | 03:44 | I am going to jump over in my
JavaScript, and uncomment a little line
| | 03:48 | there where I am creating mainTitle and just
using document.getElementByID of mainTitle.
| | 03:54 | I'm now going to uncomment just a
console.log message and ask for mainTitle's
| | 03:58 | innerHTML property, save that, jump
back over, and I'll refresh this page.
| | 04:04 | You need to have Firebug open to see that.
| | 04:11 | The console.log message is writing
out Welcome to Explore California!
| | 04:16 | So in this case, innerHTML of this
anchor tag is giving us the text inside it.
| | 04:21 | When you have a very simple tag,
innerHTML can be a good way to work with it.
| | 04:27 | A simple h1 is fine, as is an a
tag, as is even there's a paragraph.
| | 04:32 | Grabbing, for example, a div
might give you a little more.
| | 04:36 | Let's say we get a div that contains quite
a few things, like this div ID of sidebar.
| | 04:42 | If I do exactly the same kind of thing
here, let's just change that and call it
| | 04:46 | a var sidebar, and log out its innerHTML,
| | 04:55 | jump back over to Firefox, and refresh the page,
| | 04:57 | well, you see what we're getting here is
the entire contents of that div and all
| | 05:03 | its divs inside it and all its h2s.
| | 05:05 | This certainly wouldn't be anywhere
near as easy to start to manipulate as it
| | 05:10 | would be if I just wanted to change the
title or the words of a paragraph, or an h1.
| | 05:15 | So if I want a little more finesse,
I'm not going to use innerHTML.
| | 05:20 | If it's an element that contains
other elements, I might have a bit
| | 05:23 | more thinking to do.
| | 05:25 | The best way to explain how we actually
start to drill down into the interior of the
| | 05:29 | page probably comes from
learning how to create elements.
| | 05:33 | While you could use innerHTML and
manually type all the HTML yourself in your
| | 05:37 | JavaScript, that's not the best way
to do it, as we'll see in a moment.
| | Collapse this transcript |
| Creating DOM elements| 00:00 | While you could use the innerHTML
method to just write out a bunch of HTML and
| | 00:05 | dump it into a position in your document,
it's not a clean way to do it, and it's
| | 00:09 | easy to make a mistake.
| | 00:10 | The best way is to start manually
creating and inserting individual DOM element
| | 00:16 | nodes into your document, and this
is a very powerful technique to learn.
| | 00:19 | It lets you change your page on the fly
and to do it, there's always two steps.
| | 00:24 | One, you create the element.
| | 00:26 | You say I want to create a paragraph or a
heading or a list item or an anchor tag.
| | 00:32 | And step two is you then add that
newly created element to the right place in
| | 00:37 | the DOM, the right place in the document.
| | 00:40 | So here's an example.
| | 00:41 | If I imagine I've got a very simple
HTML page representing here as a set of DOM
| | 00:46 | nodes, I can see that my
body consists of three things:
| | 00:50 | an h1 heading, a paragraph, and an
unordered list with an id of abc.
| | 00:56 | That unordered list has
three list items underneath it.
| | 01:00 | And I can imagine I've already used
getElementById to create a variable called
| | 01:05 | myElement that points to that unordered list.
| | 01:08 | That will be important in a second.
| | 01:10 | So if I want to add a new list item to
this point in the DOM, a new list item to
| | 01:16 | the unordered list, what I
have to do is first, step one,
| | 01:19 | create the element.
| | 01:20 | And instead of using document.getElementById,
we use document.createElement and
| | 01:27 | I pass in a string that
says what kind of element.
| | 01:30 | In this case, it's an li.
| | 01:32 | If I wanted a paragraph, it would be a p;
| | 01:34 | if I wanted an anchor tag,
it would be an a; and so on.
| | 01:36 | Now that creates it, but it
creates it kind of out there in space.
| | 01:41 | The element exists, but it's
not part of the DOM itself.
| | 01:44 | So the next thing that I need to do, step two,
is call the appendChild method of myElement.
| | 01:52 | So I'm actually saying for the
unordered list, append the child this new
| | 01:57 | element, the list item.
| | 01:59 | JavaScript will take it.
| | 02:00 | It will make it part of the DOM and
understand its place in the document itself.
| | 02:04 | Now right now, this list item would be a
little bit basic because we haven't set it.
| | 02:09 | We haven't given it any text, and that's
usually what we expect with a list item.
| | 02:13 | Well, I could, if I wanted, use innerHTML and
just actually set the text of the list item.
| | 02:20 | And that would work, but there is a
preferable way to do it as well, or a more
| | 02:24 | exact way, which is that after we've
created the element itself, we then
| | 02:30 | create a text node.
| | 02:31 | Remember that the element and the
text they contain are actually different.
| | 02:35 | So if I've got that variable
myNewElement that points to that list item, what
| | 02:40 | I'm then going to do is use the
createTextNode method, which creates this text
| | 02:45 | node. Very similar to creating an element,
| | 02:47 | it's out there in space,
not attached to anything.
| | 02:50 | And once again, we use appendChild, except
this time we're adding it to the NewElement.
| | 02:56 | This would be the most exact, the most
specific way to start creating these DOM elements.
| | 03:03 | So let's do a demo.
| | 03:04 | So in my browser, I have a
page that I already created.
| | 03:08 | It's just a fairly regular web page.
| | 03:10 | But down here a little bit further,
I've got this area that I want to generate
| | 03:14 | some content in, and I'm actually
going to do that using JavaScript.
| | 03:19 | This blank area here, if I look at my
HTML, is actually represented by a div
| | 03:25 | with an id of trivia.
| | 03:28 | So this is the place that I want to create
new DOM elements and add them right here.
| | 03:34 | So the way to do it, if I come over to
my script.js file, I've got some code
| | 03:37 | that already exists.
| | 03:38 | I'm just going to uncomment it.
| | 03:42 | And I'm actually going to do two things here:
| | 03:43 | I'm going to create an h1 element, and then
I'm going to create a p, or paragraph, element.
| | 03:49 | So lines 2 and 3 we actually create new
variables creating those elements, but
| | 03:53 | they're just existing out there in space.
| | 03:55 | They actually aren't part of the page yet.
| | 03:57 | Well, not only that,
they don't have any content.
| | 04:01 | So if I want to do the slightly
easier way but not as exact as possible, we
| | 04:06 | could call the innerHTML on
both of these new variables.
| | 04:10 | So newHeading, which I just created,
set its innerHTML to "Did You Know?"
| | 04:15 | And the newParagraph, which I just
created, set its innerHTML to "California
| | 04:20 | produces over 17 million
gallons of wine each year."
| | 04:23 | So we have our elements, we have some
text added to them, but they're still
| | 04:28 | not part of the page.
| | 04:29 | And in fact, right down here on Line
17 and 18 I'm just going to uncomment
| | 04:33 | these lines because this is
how we add them to the page.
| | 04:38 | If you remember, the div that I
wanted to add them to is called trivia.
| | 04:42 | So we call document.getElementById
("trivia").appendChild(newHeading), we're
| | 04:48 | adding the h1, and then we call the
whole thing again, and then we say we'll now
| | 04:53 | append another child, which is the paragraph.
| | 04:56 | So if I save this and I just open
that up in the browser again, what we'll
| | 05:01 | find is that that part of the page
that was blank now has this content that's
| | 05:06 | been dynamically added.
| | 05:07 | And because it's using the same CSS
rules as the rest of the page, I have a
| | 05:11 | formatted headline with the underline
and I have the correct font showing up.
| | 05:15 | But let's just talk about the
more exact way of adding text.
| | 05:20 | We can use innerHTML, but the
alternative way is going to be below here.
| | 05:25 | It's going to require two more lines
of code, but it is a bit more exact.
| | 05:29 | And we do it similar to
creating the elements themselves.
| | 05:32 | We actually create new text nodes.
| | 05:35 | So on Line 10, I'm creating a
variable called h1Text and calling
| | 05:38 | document.createTextNode and giving it a
little bit of text to initialize itself,
| | 05:43 | and then the same thing on
Line 11 for the paragraph.
| | 05:47 | But because you create text nodes
just like elements that are just existing
| | 05:51 | disconnected out in space, what I'm
then doing is on Line 13 and 14 I'm
| | 05:58 | associating those new text nodes with
the new h1 and the new paragraph that I
| | 06:03 | created on Line 2 and 3.
| | 06:06 | And I'm leaving line 17 and 18 exactly
as they are because we still need to add the
| | 06:12 | new heading and new paragraph to our DOM.
| | 06:15 | Save that, jump back over into the
browser, and if I refresh this, we should see
| | 06:21 | absolutely no changes at all.
| | 06:24 | Again, you can make your own
decisions about which method to use.
| | 06:27 | Creating text nodes separately does
mean typically writing a little bit more
| | 06:31 | code, but it is a more exact
and more specific way to do it.
| | 06:35 | So while the process is always going
to be a step one, create the element,
| | 06:38 | step two, add it to the DOM,
| | 06:40 | there is an alternative to appendChild,
although that is the most common one.
| | 06:45 | Instead of just pointing to the parent
element and saying appendChild, we also
| | 06:49 | have the choice of insertBefore.
| | 06:51 | So if you want a bit more flexibility
about where our new element is inserted
| | 06:56 | into the DOM, we can use this one as well.
| | 06:58 | Let me show an example here.
| | 06:59 | So taking the same idea of that DOM
tree that we had before, appendChild will
| | 07:06 | always add that new list item right at the end.
| | 07:10 | It will always add it, as in
this case, the fourth list item.
| | 07:13 | But what if I didn't want that?
| | 07:14 | Well, step one is still the same:
| | 07:17 | create the element.
| | 07:18 | We're creating it there out in space.
| | 07:20 | Now the second step here is I need to
grab hold of a variable that points to, in
| | 07:25 | this case, let's say the second list
item, and I'm going to do this by calling
| | 07:30 | getElementsByTagName, because that
second list item doesn't have an ID.
| | 07:35 | So I'm first calling
myElement.getElementsByTagName, saying I want to find all
| | 07:41 | the list under the unordered list.
| | 07:44 | And then I'm using the square
brackets and saying number one, which if you
| | 07:47 | remember, we're going to use
zero-based arrays, so the first one would be at
| | 07:51 | position 0, the second one at
position 1, the third one at position 2.
| | 07:56 | So I now have a variable, secondItem,
that points to the second list item.
| | 08:00 | And what I can do is use the
other way of adding to the DOM.
| | 08:05 | Instead of appendChild, I call
myElement.insertBefore and the two pieces of
| | 08:11 | information I give it is what's the
new element and what's the element you
| | 08:15 | want to insert it before, in this case,
secondItem, at which point it will
| | 08:19 | reshuffle that arrangement and insert my new
list item into that very specific point in the DOM.
| | 08:26 | So most of the time, you'll be using
appendChild, but insertBefore can come
| | 08:29 | in very handy as well.
| | Collapse this transcript |
|
|
6. Working with Events and Event ListenersIntroduction to JavaScript event handling| 00:00 | So we're starting to write some deeper
code, but it's still happening as soon as
| | 00:04 | the browser gets to it.
| | 00:05 | And that's not a very interactive situation.
| | 00:08 | We're not reacting to
anything the user is doing yet.
| | 00:11 | We can fix that by working with events.
| | 00:14 | Maybe I've got some JavaScript that I
only want to run when a link is clicked on
| | 00:17 | the page. Or if the user tries to
submit a form, I want to make sure that
| | 00:21 | they've filled out the form first.
| | 00:24 | And I want to make sure that not only
has the page loaded, but also all of the
| | 00:28 | assets it's linking to, including
images and style sheets and so on.
| | 00:31 | And we can do all of these
things and a lot more with events.
| | 00:35 | Now here's the thing with events.
| | 00:37 | It's common for someone new to
JavaScript or new to programming to get a little
| | 00:41 | puzzled about your role here.
You're thinking, "Am I supposed to write the event?
| | 00:45 | How do you describe an event?"
| | 00:47 | Well, you don't, because here's the deal.
| | 00:50 | The events are already happening.
| | 00:52 | They've been happening all along.
| | 00:55 | When the page is loaded, that's an event;
| | 00:57 | when the user clicks a
button, that's another event;
| | 00:59 | when they move their mouse,
that's a whole bunch of events;
| | 01:02 | when they scroll the screen, that's an event;
| | 01:04 | when they click a form field, that's an event;
as they type, every key press is another event.
| | 01:09 | Events are going on all the time.
| | 01:12 | You have to decide which ones you care about.
| | 01:16 | See, these events are built into JavaScript.
| | 01:18 | They're part of JavaScript,
and there are special words to describe them.
| | 01:22 | You'll see them typically written all
lowercase, and they begin with the word on,
| | 01:26 | so onload, onclick, onmouseover, onblur,
onfocus, and we'll see several of these
| | 01:32 | in the next couple of movies.
| | 01:34 | But you don't write the event itself.
| | 01:36 | You write what's called the event handler or
the event listener, whatever term you prefer.
| | 01:42 | You write your function and you
volunteer to handle or to listen out for one or
| | 01:47 | more events, so that you
can respond when they happen.
| | 01:50 | And I'm going to talk about and cover three
ways you can react to an event in JavaScript.
| | 01:55 | One is the simplest and the ugliest way.
| | 01:59 | You can just write JavaScript code
directly in your HTML, so if you have a
| | 02:03 | button tag in your HTML,
you can use that word onclick--
| | 02:07 | again, this is the event--onclick = and
in this case I'm just directly typing in
| | 02:12 | JavaScript, the alert('Hello, world') here.
| | 02:15 | I'm not a fan of this
method, for multiple reasons.
| | 02:18 | It's going back to having script mixed
in with our HTML, which I'd like to avoid
| | 02:22 | as much as I like to avoid
CSS mixed in with our HTML.
| | 02:26 | While you can include multiple
statements here separated by semicolons, really,
| | 02:31 | how much do you want to write like this?
| | 02:33 | And if we did this a lot, we
wouldn't be reusing code like we can with
| | 02:37 | an external file, and there's no way to
make this friendly if JavaScript is disabled.
| | 02:42 | But you will see it from time to time.
| | 02:44 | The second way is to use the name of the
element, then a dot, then the name of the event.
| | 02:49 | So window.onload means the
onload event of the window object;
| | 02:54 | nameField.onblur means the onblur
event of the nameField object; or quite
| | 02:59 | classically, just myelement.onclick.
| | 03:02 | When they click a DOM element, we want
to do something, so we use the equal sign
| | 03:06 | and then this following format:
| | 03:08 | the word function(), and then the
opening and closing curly braces,
| | 03:14 | and then you put your event handler
code inside here, whatever you want to
| | 03:18 | execute when they click that element,
whether that's one line or a hundred.
| | 03:24 | And what we're doing here is
what's called an anonymous function.
| | 03:27 | This is very, very common in
JavaScript, and you'll see it all over the place.
| | 03:32 | It might look a little weird because
usually we use the word function and we
| | 03:35 | give our function a name, but we're
not doing that here. And that's okay.
| | 03:39 | Think about the reason for a function.
| | 03:42 | We usually use a function to wrap up
a bunch of code and give it a name so
| | 03:45 | we can call it later.
| | 03:47 | Well, here, we're still using the
word function to wrap up a bunch of code--
| | 03:50 | whatever is in between the opening and
closing curly braces--but we don't have
| | 03:54 | to give it a name because we're saying
exactly when this gets executed, which is
| | 03:59 | when they click myelement.
| | 04:01 | So when this event happens, we want
to run this function, whatever is in
| | 04:05 | this block of code,
| | 04:06 | so naming it would be a waste of time.
| | 04:08 | Now one important thing here, bear in
mind, if you write this code, the first
| | 04:14 | time JavaScript reads it, it won't
actually do anything with the function.
| | 04:19 | What you're actually saying is later
on when the user clicks this element,
| | 04:23 | we execute this code.
| | 04:24 | I'm just telling you about it right now.
| | 04:26 | And because of that, there's a little
addition to this that often messes people
| | 04:31 | up when they first see it, which is
we're ending this all with the semicolon.
| | 04:37 | And it's very common for beginners to
JavaScript to look at this and go,
| | 04:40 | "I don't quite understand.
| | 04:42 | I didn't think we used
semicolons around functions."
| | 04:45 | And people get very puzzled because
they think, "When do I need a semicolon. Do I
| | 04:48 | put it at the end of a function or
don't I put it at the end of a function?"
| | 04:51 | Well, the thing about it is this:
| | 04:53 | it's nothing to do with the function.
| | 04:55 | We're not putting the semicolon
there because this is a function;
| | 04:59 | we're putting the semicolon there
because the whole thing is a statement.
| | 05:04 | We're saying myelement.onclick = this function.
| | 05:08 | That's why the semicolon goes
at the end of the block here.
| | 05:12 | The same way I put a
semicolon at the end of var a = 5,
| | 05:16 | I put it at the end of
myelement.onclick = function().
| | 05:19 | In most cases, it would work if you forgot the
semicolon, but you will see this format a lot.
| | 05:26 | And then there's the third method of
deciding to handle or register for an event.
| | 05:31 | This has one huge benefit and one huge drawback.
| | 05:37 | It's using a method called
addEventListener, which you can either call directly
| | 05:41 | on the document object or
on any element that you have.
| | 05:45 | And you give it three pieces of information:
| | 05:48 | the event--and here you actually write
it without the word on, so click rather
| | 05:52 | than onclick, mouseover rather than onmouseover--
| | 05:56 | then a comma, then the function you
want to run, and then the term false.
| | 06:00 | We're actually interested in
the first two arguments here.
| | 06:04 | What event are we listening for and
what function gets called when it happens?
| | 06:08 | This third false argument is an option
for some super-advanced event handling
| | 06:12 | that's very unusual to need.
| | 06:13 | Now the big benefit is using this
way you can actually add a listener
| | 06:19 | to multiple events. You can add one
event and have multiple listeners.
| | 06:23 | You have a lot of flexibility to
dynamically add and use its mirror image to
| | 06:28 | remove event listeners
as your script is running.
| | 06:31 | If that's the big benefit,
here's the big problem.
| | 06:34 | This is one of the very few areas
left where there is still a difference
| | 06:39 | between the browsers.
| | 06:41 | Because Internet Explorer,
prior to IE 9, does not have the addEventListener
| | 06:46 | function. It has its equivalent which is
the attachEvent method, which takes two
| | 06:53 | parameters. Same idea;
| | 06:54 | it's the event name
itself and then the function.
| | 06:57 | It's the same concept,
but it's a different name.
| | 07:00 | And that's a small difference that
makes a big difference because to use this
| | 07:05 | we now need to write code to detect
whether or not these functions exist.
| | 07:10 | And if I wanted to be agnostic about the
browser, what I'd probably typically do
| | 07:15 | is write my own little helper method.
I'd write my own function called say
| | 07:19 | addCrossBrowserEventListener,
and I could pass it information.
| | 07:24 | And it would do a little bit of scanning to
see, does the EventListener function exist?
| | 07:29 | If it does, we'll use the
addEventListener function;
| | 07:31 | if it doesn't, we'll use the attachEvent one.
| | 07:34 | Now here's the thing.
| | 07:35 | I have written a lot of cross-browser
detection code in my time, but these
| | 07:40 | days I do my best to avoid ever
handwriting functions that deal with
| | 07:44 | cross-browser issues.
| | 07:46 | If I need the benefits of
addEventListener and attachEvent, I will not write my
| | 07:51 | own code to handle the difference.
| | 07:52 | I'll use one of the free
third-party JavaScript libraries like jQuery.
| | 07:57 | A big part of what they do is provide
excellent cross-browser functions for
| | 08:02 | situations like this.
| | 08:03 | We'll talk about these libraries a little later.
| | 08:06 | Because of this reason, in this course
I'm going to be using the simpler, more
| | 08:10 | straightforward, but cross-browser
compatible methods of creating event handlers.
| | Collapse this transcript |
| Working with onClick and onLoad events| 00:00 | So now I'm going to write some code to
respond to common events, and if there are
| | 00:04 | two events in any programming language
that are the most common, it's clicking
| | 00:08 | on something and loading something.
| | 00:10 | So I have a regular HTML page here
with some images and CSS linking to a
| | 00:16 | JavaScript file that's actually
currently empty, and I have both of those just
| | 00:20 | open in my editor here.
| | 00:22 | So the simplest way that I could cause
something to happen is like I have on
| | 00:27 | Line 28 here where I just have the
onclick = inline code in my HTML itself, and
| | 00:35 | no particular surprise on what this is
going to do. If I click that button, I'll
| | 00:39 | run that alert message.
| | 00:41 | But we are not going to
do any more code like this.
| | 00:43 | We are going to do it properly.
| | 00:45 | So I am going to jump across into my
script.js, which is already being linked
| | 00:49 | to, but there's no script in it yet.
| | 00:51 | Now it's easy to think that we
need a button or a link to click on.
| | 00:55 | We can support the idea of
clicking on anything in our document.
| | 00:59 | Click is a very generic event.
And we mentioned that we need to
| | 01:02 | write element.event,
| | 01:04 | so what's an element?
| | 01:05 | Well, one of the top-level
ones I have here is document.
| | 01:09 | The document is an element itself.
| | 01:11 | document., and event name, I'll say
onclick =, and this is where we then write
| | 01:18 | what's called the anonymous function.
| | 01:20 | This isn't the only way of doing it
here, but this is the most common way.
| | 01:24 | So the word function, opening and
closing parentheses, and opening and closing
| | 01:28 | curly braces that contain
whatever code I want to execute.
| | 01:32 | In this case, I am going to do something simple,
| | 01:34 | alert ("You clicked somewhere in the document").
| | 01:43 | So I jump over to the browser,
| | 01:44 | I reload the page, and as soon as I
clicked, I should get that alert message.
| | 01:49 | The only thing I have to be careful
with would be clicking on perhaps one of
| | 01:52 | these links, which actually won't go
anywhere right now and get a missing page.
| | 01:56 | But you can see I don't have to click
explicitly on a button; it can react to it anywhere.
| | 02:03 | Now it's probably not all that useful to
make the entire document respond to clicking.
| | 02:08 | So what we could do instead, I am
going to jump over and do a slightly
| | 02:14 | different one here.
| | 02:15 | First, I'm going to create a variable.
| | 02:27 | First, I am going to create a variable
and just grab hold of an image which has
| | 02:32 | the ID of main image, because if I want
to respond to an event, I don't have to
| | 02:37 | respond at the document level.
| | 02:38 | I don't have to say document.onclick.
| | 02:40 | I can use any element.onclick.
| | 02:43 | So now I got that image, I could say
myImage.onclick = another anonymous
| | 02:51 | function, and we'll pop up in the
message, You clicked the image.
| | 03:02 | Save that, jump back over into
the browser, and refresh this page.
| | 03:08 | Now if I click the image, I should get
the message, "You've clicked the image,"
| | 03:12 | though having said that, this is
also considered a document click,
| | 03:16 | so I'll get that other event as well.
| | 03:19 | If I click somewhere off the image,
I'll just get "You've clicked somewhere in
| | 03:22 | the document," but it can also target the
image, which again, has the document as well.
| | 03:29 | So you can target this event
handling at any level that you want to.
| | 03:34 | You don't have to have a
button or a link to click on.
| | 03:38 | It can be any element on the page.
| | 03:40 | Up to this point, what I've done is I've
recommended always putting any links to
| | 03:45 | external JavaScript files right here at
the end before the closing body tag, and
| | 03:49 | that is a good rule.
| | 03:51 | However, it doesn't guarantee that
your page and all its assets are loaded.
| | 03:55 | If you're loading CSS files, images,
et cetera, you might actually hit and run
| | 04:00 | your JavaScript before everything
has been fetched from the server.
| | 04:03 | So it's very common to make sure
everything is loaded before we start running
| | 04:07 | any JavaScript at all.
| | 04:08 | I am going to emulate this by
just doing a little trick here.
| | 04:11 | I am going to grab the script tag and
just put it up here somewhere in the
| | 04:16 | head of the document.
| | 04:17 | So it's going to be loaded as soon as
the browser sees Line 7, before it even
| | 04:23 | gets onto the body here.
| | 04:24 | I am going to jump over into script.js.
| | 04:27 | I am just going to remove that
document.onclick function, because I don't
| | 04:32 | really need it here.
| | 04:34 | I just want one responding.
| | 04:36 | So still I have that code to say when
you click the image pop up an alert box.
| | 04:42 | I jump over to the browser.
| | 04:43 | I am going to reload this page.
| | 04:45 | Now if I click this image, I don't
have anything, because the problem here is
| | 04:54 | that the browser is trying to execute
this JavaScript as soon as it gets to it.
| | 04:59 | It's trying to grab this element called
mainImage, but it's trying to run that
| | 05:05 | around about here, before it
passes the rest of the page.
| | 05:08 | It doesn't have an element called mainImage.
| | 05:10 | So it can't add itself to onclick.
| | 05:13 | So how do we deal with this?
| | 05:14 | Well, this is a very, very common issue,
and the event we want to respond to is
| | 05:20 | the onload event of the window object,
not the clickevent of the myImage object
| | 05:26 | or the mouseover event of
the document, but window.onload.
| | 05:31 | Now we haven't really touched
on the window object very much.
| | 05:34 | We've been staying
focused on the document object.
| | 05:37 | The window actually
represents a full browser window.
| | 05:41 | It is actually the top-level object in
JavaScript. It contains the document object.
| | 05:46 | And it's this that can tell
us when everything is loaded.
| | 05:49 | I use the same format, the.event
format here, and I'll just do an
| | 05:54 | anonymous function.
| | 06:03 | So call any other functions,
"prep anything we need to." In fact, a good idea
| | 06:07 | here is that what I might do
is create a new named function.
| | 06:15 | Let's imagine that we had multiple
event handlers that we were worried about.
| | 06:20 | So I am going to grab my code and
paste it in there, so that when this
| | 06:30 | function is called, it will try and
add an event handler to the image, but I
| | 06:35 | am going to make sure that function doesn't get
called until the document has completely loaded.
| | 06:42 | Save that jump, back over into the
browser, and now, even though the JavaScript
| | 06:48 | is loading immediately, we should get
our successful event handlers popping up
| | 06:54 | here, because the browser is reading the code.
| | 06:59 | It's understanding the function and
then it's hitting this window.onload and
| | 07:03 | realizing, okay, I'm only going to
call Line 18 after the document has fully
| | 07:08 | loaded, regardless of where the
script was placed in the HTML.
| | 07:12 | Now as we get more complex, one thing
to watch out for is that you should only
| | 07:17 | write this window.onload function
once per page, and if you ever link to
| | 07:22 | multiple JavaScript files and find out
that you've got multiple files trying
| | 07:27 | to do the same thing, it's only the last one that's
going to win. But window.onload is a very common
| | 07:32 | event and one you are going to react to a lot.
| | Collapse this transcript |
| Working with onBlur and onFocus events| 00:00 | Here are two more events, very
useful when working with forms.
| | 00:04 | No doubt you've seen this one before.
| | 00:05 | You're filling out a form on a web site
and one or more of the fields actually
| | 00:10 | has a value already pre-filled in,
perhaps prompting you what to do.
| | 00:15 | You can either click in there or tab into
that location and that text will disappear.
| | 00:20 | However, if I tab out of it again, the
text comes back to prompt me that I need
| | 00:24 | to put something in there.
| | 00:26 | This is very easy to do using the
onfocus and onblur events in JavaScript.
| | 00:32 | Every one of our form elements here
gets an onfocus event kicked off when we
| | 00:37 | click into it, or when we hit the Tab
key and tab into it, and when we leave it,
| | 00:43 | that element gets the onblur event.
| | 00:46 | So to create something like this
behavior is very simple indeed.
| | 00:50 | Let's take a look at the
HTML, then the JavaScript.
| | 00:54 | My HTML is nothing special.
| | 00:57 | I have a form created and I have an
input element here for the email, and it
| | 01:02 | has got an ID of email.
| | 01:05 | And simply, in the JavaScript, Line 2
grabs a hold of a reference to that email
| | 01:11 | field, and then we add two event handlers to it.
| | 01:16 | For my emailField.onfocus we'll
execute this function, and for onblur we'll
| | 01:21 | execute this function.
| | 01:23 | So onfocus, meaning we click into it,
| | 01:25 | what it's asking is if the value of
that text field is your email, all in
| | 01:30 | lowercase, then we're going to set it to
blank and allow someone to type in a value here.
| | 01:36 | Now, notice that what we're doing when
we're trying to grab the contents of the
| | 01:39 | textbox, it's the .value property,
not .innerHTML, but .value, and that's the same
| | 01:46 | for pretty much every form field.
| | 01:48 | So the value is your email,
we'll blank it out.
| | 01:51 | However, when they leave and we kick
off the onblur event, it's going to ask,
| | 01:56 | well, did they leave leaving that value
as blank, and if so, what we're going to
| | 02:00 | do is change it right back to your email.
| | 02:04 | So, very easy to do.
| | 02:06 | if we leave that form field, the
value changes to your email. If we click
| | 02:10 | back in, it goes blank.
| | 02:11 | If I type in a value, it will not
overwrite it with your email, although that
| | 02:17 | might not be what we want.
| | 02:19 | I'm just checking that
they typed something here.
| | 02:22 | If I wanted to write a little bit of
code to check it was a valid email format,
| | 02:26 | I could use something called regular
expressions, and that's available in
| | 02:30 | JavaScript to do pattern matching.
| | 02:32 | But regular expressions are another movie.
| | Collapse this transcript |
| Working with timers| 00:00 | It's very common to want to trigger
some JavaScript to run but to run later, to
| | 00:05 | call a function after 60 seconds, or to
call a function every 5 seconds, and we
| | 00:10 | use timers for these.
| | 00:11 | Slideshows would use timers, clocks
would use timers, and there are lots
| | 00:15 | more uses for them.
| | 00:17 | While timers aren't officially events
in JavaScript, they can feel a little bit
| | 00:21 | like it, so we will talk about them here.
| | 00:23 | Really, there are only two
methods that we are interested in.
| | 00:28 | I'm looking at a little bit of code here,
but there is nothing to do with timers just yet.
| | 00:31 | I have a function defined called simpleMessage.
| | 00:35 | I'm going to add just a call to setTimeout.
| | 00:38 | We can just call setTimeout directly the
same way we could call alert or console.log.
| | 00:44 | It's always available.
| | 00:46 | All I need to give it is two things:
| | 00:48 | the name of the function I want to call--in
this case simpleMessage, comma--and the interval.
| | 00:55 | Now, setTimeout is used in milliseconds,
| | 00:58 | so if I wanted to say pop up five
seconds later, I'll put in 5000.
| | 01:03 | Finish that statement.
| | 01:05 | We can ignore anything that's below it.
| | 01:07 | Right now, it's not being used yet.
| | 01:08 | I am going to save that, and I'm going
to refresh the page that I am on that's
| | 01:12 | actually using this.
| | 01:14 | Open that up, and then hopefully in
about 5 seconds, we get the alert box.
| | 01:21 | Yes, I agree, not very
exciting, but it proves the point.
| | 01:25 | Now, when I use
setTimeout, it just happens once.
| | 01:28 | It hits that line of code and says,
"I am going to do this once and that's it."
| | 01:32 | We also have a different one called setInterval.
| | 01:36 | setInterval takes exactly the
same format, but it repeats it.
| | 01:43 | In this case, setInterval will call the
function called changeImage every five seconds.
| | 01:49 | Now, what do I have going on here?
| | 01:52 | Well, just to break it down, what I am
doing is on line 10 I'm grabbing hold
| | 01:57 | of an element of the page called
mainImage, and if I look at the HTML here, all
| | 02:05 | I have is that mainImage isn't a regular
image tag in the main section of my document.
| | 02:11 | So I am grabbing hold of that,
so I can change the source of it.
| | 02:16 | On line 12 and 13 I am creating an array,
using the shorthand format within the
| | 02:22 | square brackets, and all I'm putting in
it is six paths to images, and these are
| | 02:28 | just some images I have locally in
the _images folder that I have here.
| | 02:36 | I've gone through and manually entered these.
| | 02:38 | Now what I am going to do is rotate around them.
| | 02:41 | So I am creating my own little index
here, which I will set at position 0, and
| | 02:46 | then in my function called changeImage
I'm going to reach into that image
| | 02:51 | and set its source attribute to
whatever the current contents of the array
| | 02:57 | are at the current index.
| | 03:00 | So the first time we call it it
will say, "Well, my index is set to 0.
| | 03:04 | I will grab the image that's called overlook.
jpg, and just add that entry to the image tag."
| | 03:10 | Then we add one to the imageIndex.
| | 03:13 | We check to see if the index is larger
than the length of the array; it isn't.
| | 03:17 | So I am done with the function.
| | 03:19 | But setInterval is still
ticking, and in five more seconds
| | 03:23 | it's going to call changeImage again.
| | 03:25 | We then grab the second element, we
change the attribute, we increment the
| | 03:31 | index, and we just keep going.
| | 03:34 | So if I save this, go back over to my
page, and hopefully, after about five seconds
| | 03:44 | we change to one image,
| | 03:46 | we wait a few more seconds, it will
change to the next one, and as we watch, it
| | 03:49 | would keep going and just start to loop around.
| | 03:53 | A very simple use, and all we're
really doing here is the setInterval.
| | 03:58 | But both setTimeout which is the
single one and setInterval which is the
| | 04:02 | repeating one have their mirror images,
| | 04:05 | the ability to both clearTimeout and
clearInterval. So just because we start
| | 04:11 | something repeating, doesn't mean
we always want to go on that way.
| | 04:15 | The question is, how do we do it?
| | 04:16 | Well, here's the interesting thing.
| | 04:18 | When we call setInterval--I am just
going to bring it up a little bit so I
| | 04:22 | can see more to it--
| | 04:24 | this function actually returns
a value, and I'm going to store it.
| | 04:28 | I didn't care before, but now I do.
| | 04:30 | I'm going to create a new variable called
intervalHandle. That's as good a name as any.
| | 04:36 | It's just going to be a variable that
connects me to a little bit of memory that
| | 04:40 | says 'I understand what this interval is doing.'
| | 04:43 | What I am then going to do is say,
when somebody clicks on the image--so I'll
| | 04:48 | use the myImage.onclick event = function(),
just a small anonymous function--
| | 04:55 | I'm going to call, instead of
setInterval, I am going to call
| | 04:58 | clearInterval, passing in that
interval handle, the variable that was
| | 05:06 | returned from calling setInterval.
| | 05:09 | Now, you might think, "Well what does that do?"
| | 05:10 | It allows me to create this ticking
clock, this setInterval, and if I want to
| | 05:17 | pass that value right into
clearInterval then it knows which one to clear.
| | 05:22 | The idea of this is I could have
multiple intervals kicking off in my JavaScript.
| | 05:27 | I don't want to clear all
of them or none of them;
| | 05:29 | I need to know one at a time.
| | 05:31 | So I'll save that, jump back over,
and open my page again, and we should
| | 05:35 | have the ticking clock going on.
The setInterval should be refreshing this
| | 05:40 | image every five seconds.
| | 05:44 | But if I click on it, single-click,
I'm not asking for any feedback, but that
| | 05:50 | setInterval should now be cleared.
And as you notice, the picture is not
| | 05:54 | ticking over anymore.
| | 05:56 | That is simply timers in JavaScript.
| | 05:59 | Working with timers in JavaScript
really boils down to those four methods:
| | 06:03 | setTimeout to perform a single action
after a delay, setInterval to repeat it
| | 06:10 | after that delay and just keep
on repeating, and their evil twins
| | 06:14 | clearTimeout and clearInterval.
| | Collapse this transcript |
|
|
7. Debugging JavaScriptCommon JavaScript errors| 00:00 | We may be creating web pages, but this
is programming, and no matter how good we
| | 00:04 | get, we'll spend less time writing code
and more time figuring out why the code
| | 00:09 | we wrote doesn't work.
| | 00:10 | JavaScript is a forgiving language,
but there are still common problems to be aware of.
| | 00:14 | Now when you look at a page and it
doesn't do what you were hoping, know that
| | 00:18 | many JavaScript problems have failed
silently. There will be no error message.
| | 00:22 | They just won't work,
| | 00:23 | although we can get some error message from
some of our code, and let's cover those first.
| | 00:29 | Make sure to have your JavaScript
debugger, like Firebug, open, as the default
| | 00:33 | configuration of most web browsers
won't alert you to any JavaScript issues.
| | 00:37 | They just won't work.
| | 00:39 | I'm going to refresh this page,
and with Firebug open, it's giving me a
| | 00:42 | problem here, and this is the
situation, that first, and most importantly, we
| | 00:47 | might have syntax errors.
| | 00:49 | So I'm going to jump over to Aptana.
| | 00:51 | I'll go to small JavaScript file that
I'm using here with a few of the very
| | 00:56 | common errors I want to show you.
| | 00:58 | Most of it's commented out.
| | 00:59 | I only have a few lines
of active JavaScript here.
| | 01:02 | First, and most importantly,
you have syntax errors.
| | 01:06 | Did you miss a closing brace, a closing
bracket, or parentheses, or did you add an
| | 01:10 | extra one, because these and many
more will interfere with any of your
| | 01:14 | JavaScript being understood.
| | 01:16 | One of the things you'll often see
programmers do is when they are typing, say,
| | 01:19 | if statements, they will actually type
the opening and closing parentheses and
| | 01:23 | the opening and closing curly braces
before they then go back and start filling
| | 01:27 | the things out, just to make sure
that they are not messing it up.
| | 01:31 | Now if I have code and there is a
problem with this code here, over in Firebug
| | 01:35 | it's actually saying that I've got a
missing colon after property id.
| | 01:39 | Now that message itself might not be
very helpful, but when you do see messages
| | 01:45 | that don't appear to make sense, you
just need to start looking at your code.
| | 01:48 | Now, that's the message Firebug would
give me. If you're using the Developer tools
| | 01:52 | in any of the different browsers, they
will often give you a different message.
| | 01:55 | What I'm missing here is the
closing parentheses after myFunction name.
| | 02:00 | I am going to save that, go
back in and refresh the page.
| | 02:04 | Now I've got an unterminated string literal,
and it is complaining about a particular line.
| | 02:10 | If I even click the line, it
would take me straight to that.
| | 02:13 | What it appears to be
there is another syntax error.
| | 02:16 | I don't have the closing double quote.
| | 02:18 | I'm going to go back and drop that one
in, save that, back over into Firefox,
| | 02:24 | refresh the page, and I actually get the normal
log message, which was what I was hoping for.
| | 02:29 | But even after your syntax is
correct and it's understood by the browser,
| | 02:34 | there are still millions
of mistakes that can happen.
| | 02:36 | Now let's go through some common ones here.
| | 02:38 | So I'm going to just comment this code
out, because we've solved that one, and
| | 02:44 | talk about possibly one of
the most common situations here.
| | 02:48 | You create a function called, in this case,
myFunction, and you call it, or so you think.
| | 02:54 | If I save this code, I go back into
the browser and refresh it saying,
| | 02:58 | myfunction is not defined.
| | 02:59 | This is one of the situations that
will actually cause an error in any of the
| | 03:04 | JavaScript debuggers.
| | 03:06 | You're trying to call a function that
doesn't exist, whether that is because of
| | 03:10 | this situation just a typo.
| | 03:12 | I've called it a lowercase f for
function when I'm calling it, but I defined it
| | 03:16 | with an uppercase F. Saving that, we
refresh that page, and everything is working again.
| | 03:22 | So calling a function that doesn't
exist, a very common cause of JavaScript
| | 03:27 | errors, and very common also, that you
do a typo in some of the DOM methods,
| | 03:33 | such as getElementByID.
| | 03:36 | In this case, this wouldn't work.
| | 03:38 | If I save this, refresh this,
I'll get a slightly different message:
| | 03:42 | document.getElementByID is not a function.
| | 03:45 | And you might be sitting and thinking,
"Of course, it is. I've used it a hundred times."
| | 03:49 | But of course, case sensitivity
here, the D at the end of getElementByID
| | 03:54 | should be lowercase.
| | 03:56 | It's giving you a slightly different
message here, because this is considered a
| | 04:00 | method of an object rather than a function.
| | 04:03 | Again, depending on what
browser you're using, you may even see
| | 04:06 | different messages for that.
| | 04:08 | The equivalent of that with your own
code might be that you say create an
| | 04:12 | array, such as I'm doing here on line
29, and I'm trying to call one of the
| | 04:16 | object methods here called reverse,
but I spelled it incorrectly, and we're
| | 04:21 | going to get that equivalent there:
myArray.revers is not a function--which is of course true.
| | 04:26 | So comment goes back out and moving on.
| | 04:28 | Now couple of situations
we've talked about before.
| | 04:32 | One is if you're creating a variable
and calling document.getElementById, but
| | 04:37 | there is any chance that actual
part of the page hasn't loaded yet,
| | 04:41 | you'll only have an undefined variable here.
| | 04:43 | This won't actually cause an error.
| | 04:46 | Your code just won't work the way you
expect it to, and that happens more and
| | 04:51 | more as you get better with your code.
| | 04:53 | You're not going to get those very
obvious errors about functions not existing;
| | 04:57 | it's just not going to work.
| | 04:59 | Classic situation, of course, being this one.
| | 05:01 | On line 41, I create a variable, a = 10,
line 42 var b = 20, and then I have an if statement=,
| | 05:08 | if (a = b), or so I think.
| | 05:10 | Now in this case, I think a should
never be equal to b, but I'm doing the
| | 05:15 | assignment instead of equality.
| | 05:18 | So in my own mind I would never expect
this message to come out, but of course
| | 05:22 | this is exactly what's going to happen.
| | 05:25 | Now notice there is no error message in
Firebug, because technically the syntax is correct.
| | 05:30 | But I'm getting this console.log, that
"Something is wrong with the universe,"
| | 05:34 | because we're doing
assignment instead of equality.
| | 05:37 | We're setting a = b here, not checking a = b.
| | 05:42 | A mistake that all programmers in
C-based languages will run into once in a while.
| | 05:47 | We'll change that, swap back over and I
should have the message, "This is what I expect!"
| | 05:51 | which of course it is.
| | 05:52 | Now again, moving on to a couple of
things that would cause errors in other
| | 05:56 | languages but don't officially cause
errors in JavaScript, even though the
| | 06:01 | behavior might not be what you want.
| | 06:03 | Let's say this one, for example.
| | 06:05 | I've defined a function called calculateSum.
| | 06:08 | It takes three parameters--a, b and c--
and returns the value of those added together.
| | 06:13 | Then a little later on I'm going to call it.
| | 06:16 | I'm going to call calculateSum, passing
in two parameters, and storing whatever
| | 06:21 | comes back in my variable
called result, and then writing out
| | 06:24 | console.log(result).
| | 06:26 | Save that, jump back over into the browser.
| | 06:28 | Now, this is not an error.
| | 06:31 | All that I'm doing is writing out
the contents of that variable, which is
| | 06:35 | technically not a number.
| | 06:38 | But I'm not getting any
problem in the status bar.
| | 06:40 | It's just an unexpected result, not an
error, and those are two very different things.
| | 06:44 | And of course this is because I am
allowed to call a function passing in less
| | 06:50 | parameters than it was defined with.
What's happening here is that c would be
| | 06:55 | accepted as undefined.
| | 06:57 | Then the code tries to add three together.
| | 07:00 | If you are try and add an undefined
variable together, that doesn't make sense,
| | 07:03 | so the result is not a number.
| | 07:05 | Now, there are of course a million ways
your code can fail, but looking out for
| | 07:10 | these basic situations will
clear up a lot of those core issues.
| | Collapse this transcript |
| Using Firebug| 00:00 | So we've been using Firefox with Firebug,
although these days every modern web
| | 00:05 | browser has the equivalent tools.
| | 00:07 | Safari has their developer tools menu,
as does Internet Explorer, as does Chrome,
| | 00:12 | Opera has Dragonfly, and without
exception, these days, they are all very, very
| | 00:16 | good, but Firebug is certainly the best known.
| | 00:20 | Now we've been mainly using it so far
for the Console panel to view console
| | 00:24 | messages and to type JavaScript,
but it's much more useful than that.
| | 00:28 | If you haven't used this already, you
can use the HTML tab to actually scan and
| | 00:33 | expand the HTML that you're using.
| | 00:35 | If you notice that as I'm mousing over
different sections here, it's actually
| | 00:38 | highlighting in the top part of the page.
| | 00:41 | And you can view the DOM, the actual
Document Object Model of this page.
| | 00:46 | I can see the document here, start to
open that up, and drill down inside it.
| | 00:51 | The DOM is very useful, but it can be
a little intimidating at first because
| | 00:54 | you'll realize there is a lot more
going on with the DOM than just a few nodes.
| | 00:59 | You quickly see that each node has many
more properties than we could cover in
| | 01:03 | this course, but you can view the
properties of a particular node.
| | 01:06 | I'm looking at document right now.
| | 01:08 | I can see if it has any
childNodes. Yes, it does.
| | 01:10 | Here is HTML, drill down into that.
| | 01:13 | Does it have childNodes? Yes, it does.
| | 01:15 | It has the head section with a blank line
between them, which is technically a TextNode.
| | 01:20 | Open the body. Does it have
childNodes? Well, I'd hope so.
| | 01:24 | Yes, it's got div. It's got script.
| | 01:25 | It's got TextNodes itself.
| | 01:27 | And you can also scan to figure out if
any of these have properties that you
| | 01:31 | might be interested in.
| | 01:32 | Now one good thing is if you're much
happier with HTML, and most people are, at
| | 01:36 | least to begin with, you could drill
down into your HTML, say, into the footer
| | 01:41 | and into a footermenu section, find a
particular place, say, such as this h3, and then
| | 01:47 | use the Context menu, right-click or
Ctrl+Click depending on what operating
| | 01:51 | system you have, and click Inspect in DOM
tab and it would drill you down directly
| | 01:56 | into the particular node that you're
looking at here, which if I start browsing
| | 02:01 | through, I can even see
that this one has childNodes.
| | 02:04 | It's got one childNode and at position
zero, it's the TextNode with the contents
| | 02:09 | Quick Nav inside it.
| | 02:11 | Now one thing worth pointing out with
this is if you are using JavaScript to
| | 02:16 | change DOM content after your HTML
has loaded, know that you won't see your
| | 02:22 | changes if you're just used to the
View Source feature of the browser.
| | 02:25 | For example, I have a title up here
that was actually replaced by some
| | 02:28 | JavaScript--tried to make that reasonably obvious.
| | 02:30 | Now if I right-click somewhere and
click the option to View Page Source,
| | 02:34 | which you'll get in any browser, the
actual section that that originally was
| | 02:39 | had the word Mission in it.
| | 02:41 | So the View Source still has the old content.
| | 02:43 | This is in the h1 called pageID.
| | 02:46 | However, if I'm using Firebug, either in
the DOM or in the HTML, and I can drill
| | 02:51 | down into the particular
sections that's in mainContent here,
| | 02:54 | I've got the pageID with
"This title was replaced by JavaScript."
| | 02:58 | So Firebug is actually giving me
the more up-to-date version, which is very
| | 03:02 | useful if you're starting to
manipulate the DOM in JavaScript.
| | 03:05 | But the panel that we'll get more and more
interested in is the script part of Firebug.
| | 03:11 | That's telling me a message
here that it's disabled right now.
| | 03:14 | I'm going to enable it
and then reload the page.
| | 03:16 | And what this does is let me view all
the JavaScript being used by this page,
| | 03:21 | whether that's inline in the HTML,
and I have a little bit here, and that was
| | 03:26 | just to prove this point that some
JavaScript actually in the HTML itself that
| | 03:29 | it would show me. Or if I'm using a
separate file, which I'm also doing,
| | 03:34 | I can click on this dropdown menu here
at the top, and it allows me to switch
| | 03:38 | between the different files
that have JavaScript in them.
| | 03:41 | That's quite common that you'll
actually see several files here when you're
| | 03:45 | using this dropdown.
| | 03:46 | And the best thing about this
panel is that it will allow us to do
| | 03:50 | JavaScript debugging.
| | 03:51 | We would be able to follow this code as it runs.
| | 03:55 | We can set breakpoints in our code to
automatically pause when we're about to
| | 03:59 | hit that line, allow us to read the
current values of variables, and step through
| | 04:03 | the code line by line to
really understand what's going on.
| | Collapse this transcript |
| Going through a debugging session| 00:00 | So here is an example debugging session.
| | 00:02 | I'm going to open up a page
that's given me problems right now.
| | 00:06 | Now, it's not actually given me any
JavaScript errors; in fact, the JavaScript is working.
| | 00:10 | I have some script that's changing the
message on this page every few seconds,
| | 00:14 | and this seems to be working just fine.
| | 00:15 | I can see that rotate. The problem is if
I leave it long enough, we're hitting a
| | 00:20 | message I wasn't expecting,
| | 00:22 | undefined, which I can tell is
something weird going on with JavaScript.
| | 00:26 | So what I'm going to do is open up the
Firebug panel, which if I didn't have
| | 00:32 | it opened before, is likely to give
me a message like this that the Script
| | 00:35 | panel was inactive.
| | 00:36 | I need to reload it to activate everything here.
| | 00:39 | I can check that the console is
giving me no errors, and that is the case.
| | 00:42 | There are no errors.
| | 00:43 | There are no messages here, and that's
because my syntax is actually correct.
| | 00:47 | There aren't errors in my syntax.
| | 00:48 | There are errors in my logic, and I
want the debugger to help me find them.
| | 00:53 | So let me explain what I'm doing here.
| | 00:55 | At the top of the page, line 1,
I'm creating a message array with a few messages
| | 01:00 | in it, just using the array shorthand.
There are actually just three messages
| | 01:04 | in it. And then I'm creating a variable
that can hold my current position in the array.
| | 01:09 | We start off with at zero.
| | 01:11 | I then have a function called deeperFunction--
| | 01:13 | we'll go into that in a moment--
another function called simpleFunction, and
| | 01:17 | another function called changeMessage.
| | 01:19 | It is best to explain these
by going from the bottom up.
| | 01:22 | Here I have the classic window.onload
anonymous function, so after the page and
| | 01:28 | all its assets are loaded,
I simply run one line of code, a call to
| | 01:32 | setInterval, which is going to set up
a repeating call to the changeMessage
| | 01:37 | function every four seconds.
| | 01:40 | So I can now forget about
the lines 31, 32, and 33.
| | 01:43 | I know that changeMessage is being
called every four seconds, and I can kind of
| | 01:47 | tell that that's actually
happening, because it is doing something.
| | 01:52 | I could have written the code in the
changeMessage function to do all the work,
| | 01:56 | but to make it a bit more
interesting, it's calling another function.
| | 02:00 | This function is called
simpleFunction, which is a little bit before
| | 02:04 | here, defined on line 14.
| | 02:06 | That runs and the first thing it does
is call another function, so I'd go one
| | 02:11 | more level deep into
something called deeperFunction.
| | 02:16 | Now, this function performs a loop.
| | 02:18 | It goes around 500 times and just
creates some random numbers here.
| | 02:22 | Okay, in my example I've just got this
code so I can have some code to play with.
| | 02:27 | I don't actually do
anything with those random numbers.
| | 02:30 | But I know I'm going a few levels deep,
and then here's the code that seems to
| | 02:34 | be setting the message.
| | 02:36 | So I know something about its working,
so let's figure out what's going on.
| | 02:40 | I'm going to set a breakpoint.
| | 02:41 | Now you're allowed to set a breakpoint
on any of the lines in the gutter here
| | 02:45 | that are darker colors,
| | 02:47 | and that really just means any lines that
actually are JavaScript statements, that
| | 02:51 | they're doing something.
| | 02:52 | You can't set a breakpoint on a
curly brace or on a blank line.
| | 02:57 | So I'll create a breakpoint on
simple function and I just wait.
| | 03:00 | I don't have to reload, because a few
seconds later this function is being
| | 03:04 | called and suddenly I snap into Break mode.
| | 03:07 | The line is highlighted in
yellow and the icon
| | 03:10 | is changed here with this
little Play button, so we're paused.
| | 03:13 | The code is now paused, nothing else is
happening, the message isn't changing.
| | 03:17 | I can now step through line by line,
and to do that I'm interested in these
| | 03:21 | buttons up here at the top right.
| | 03:24 | We have the button called Continue,
Step Into, Step Over, and Step Out.
| | 03:30 | The first one is actually Rerun,
but that's not relevant here.
| | 03:33 | That allows you to quickly jump back in
time and cause an event to happen again.
| | 03:37 | It's not relevant for what we're doing,
so we're focusing on the last four.
| | 03:41 | Continue would simply say,
go again till you hit another breakpoint.
| | 03:46 | In this case, if I clicked it, we
would run through the code and it would
| | 03:49 | actually change that message again,
and then we'd break on the next call to
| | 03:53 | simpleFunction, but that didn't help me much.
| | 03:55 | So what I want is this guy, the Step Into.
| | 03:59 | Let me step line by line through the code.
| | 04:02 | If I click it once, we're going to jump
into the simpleFunction function, which
| | 04:08 | itself calls deeperFunction,
| | 04:10 | the first thing it does, so step into
that, and itself its first line is this
| | 04:15 | for loop that's going on 500 times.
| | 04:18 | If I step into that we're executing
the lines; in fact, if I just keep
| | 04:22 | clicking the Step Into button, I can
see that I'm going around of the loop
| | 04:27 | potentially 500 times.
| | 04:28 | If you notice that over here on the
right-hand side, I have this Watch window
| | 04:32 | that's actually telling me the values
of the variables that make sense here,
| | 04:36 | the local variables.
| | 04:38 | In this case I've got a variable
called foo, one called bar, and then the
| | 04:42 | variable called i, which is my loop counter.
| | 04:44 | If I don't have the Watch window
open, I can also get to those by just
| | 04:48 | mousing over the variable names and
see the different values of those things,
| | 04:52 | which is very useful.
| | 04:54 | So I could continue on, but this is
going to get a little tedious if I have to
| | 04:57 | go around 500 times before I jump back out.
| | 05:01 | If I know that I'm done here, because
it doesn't look like there's a problem,
| | 05:05 | I can come over and click
the button that says Step Out.
| | 05:09 | Now what Step Out is going to do is
take me right back to whoever called
| | 05:13 | deeperFunction, so one level back up,
| | 05:17 | which was this simpleFunction call.
| | 05:20 | And now I can continue on.
| | 05:22 | I'm going to actually click Step Into again.
| | 05:24 | This line creates a new variable to
grab the message of the current position of
| | 05:29 | the array. It then grabs a handle
to the actual message on the page
| | 05:34 | and then uses inner HTML to set it.
| | 05:37 | Once I click Step Into this line, we
should see that change up at the top of the
| | 05:41 | page: yes indeed, there it goes.
| | 05:43 | We then add want to messageIndex,
which I mouse over is now two.
| | 05:48 | Is message index greater than the length of
the array? Now there's three elements in the array.
| | 05:53 | And we don't need to reset it.
| | 05:55 | I click Step Into again,
and we go round about again.
| | 05:58 | If I keep clicking Step Into, we jump
back into the call to simpleFunction.
| | 06:03 | Now I'm looking at that call
to the deeperFunction again.
| | 06:05 | I'm thinking I don't really want to
go in there because that's going to take
| | 06:08 | me to the loop of 500 times.
| | 06:11 | Is there any way I can just execute and move on?
| | 06:14 | Well, yes there is.
| | 06:15 | It's this one here, the Step Over button.
| | 06:19 | A lot of people make a mistake with Step
Over the first time they come across it.
| | 06:22 | Step Over doesn't mean skip.
| | 06:25 | It means execute this code but if it's
a function, I don't want to go into it;
| | 06:31 | just do it and move on.
| | 06:32 | So I'll click Step Over to execute
deeperFunction without going into it. Then we
| | 06:37 | jump to the next line. And this is
saying that we want to grab a message,
| | 06:42 | whatever is at this position 2.
| | 06:44 | Notice that when I hover over new
message, because I haven't executed this line,
| | 06:48 | that is considered undefined;
that variable doesn't exist.
| | 06:51 | I click Step Into and I go back and mouse
over, and now it does exist and it has a value.
| | 06:58 | We move over again.
We change the inner HTML.
| | 07:02 | I'd add one to the messageIndex.
| | 07:04 | It's now equal to 3.
| | 07:06 | I ask, is the message index
longer than the length of the array?
| | 07:09 | No, 3 is not longer than 3.
| | 07:11 | Okay, so I don't need to reset it,
and that's my problem of course. Hopefully, at
| | 07:15 | some point this clicks with me.
| | 07:17 | The issue is the next time that I come around--
| | 07:19 | I'll actually set a breakpoint here--
| | 07:26 | I'm going to try and get whatever
is at position 3 of the messageArray.
| | 07:30 | Well, the messageArray
only has three elements to it.
| | 07:34 | That would be 0, 1, and 2.
There is no position 3.
| | 07:38 | So when that line has executed,
newMessage is still undefined, and that's
| | 07:43 | leading to our problem.
| | 07:45 | This is a very common situation with
arrays to be off by one, either one to
| | 07:50 | few or one to many.
| | 07:51 | You want to pay a lot of attention to those.
| | 07:54 | So I can pretty much figure out here
what the issue is with my code. What I
| | 07:58 | really need to do is
where this check is happening,
| | 08:02 | I need to say if message index is
greater than or equal to the length of the
| | 08:07 | array, meaning I want to
reset it if it's 3, not if it's 4.
| | 08:12 | Okay, so I can turn off that breakpoint
here and turn off that breakpoint here.
| | 08:15 | But before I go and do that,
I want to show you one more thing.
| | 08:20 | Let's say we were worried about
this code here in deeperFunction.
| | 08:24 | There is something in here I'm interested in,
but I don't want to go through 500 times.
| | 08:28 | Well, I don't have to.
| | 08:30 | A great feature is you can set a
breakpoint on a line here, but then
| | 08:35 | right-click it, use your context menu
to see that this breakpoint only stops if
| | 08:40 | this expression is true, and you can
check the contents of the variable, so if a
| | 08:44 | variable is equal to a particular
value or greater than a particular value.
| | 08:49 | In this case, I know I'm going
to try and go through 500 times.
| | 08:52 | I don't want to go through 500 times, so
what I'm going to do is actually ask if
| | 08:56 | the variable i, which is my loop
counter variable that I'm creating here,
| | 09:01 | I want to see if it's, say, a multiple of
100. The way I do that is i % 100 == 0.
| | 09:12 | This is the percent sign, which is the
modulus operator. It means i divided by 100,
| | 09:17 | what's the remainder of that?
| | 09:19 | So if i divided by 100 leaves a
remainder of zero, I want to stop.
| | 09:26 | I click Continue, and the first time
through it is actually going to stop,
| | 09:29 | because i is equal to zero. And it
say if zero divided by 100 leaves a
| | 09:33 | remainder of zero, which it does, we're
stopping. But if I click Continue again,
| | 09:39 | I notice that i immediately jumps to
100, so there is a hundred iterations of
| | 09:43 | the loop that I didn't
have to do. I click it again,
| | 09:46 | we are at 200. I click it again, we're at 300.
| | 09:49 | It's done all those iterations.
| | 09:51 | I just didn't pause on any in between.
| | 09:54 | And then I can come back over and just
click the same area in the gutter to turn
| | 09:58 | it off and click Continue.
| | 10:00 | While Firebug can get deeper--and you
should check out the documentation on
| | 10:05 | getfirebug.com--just these
abilities are being able to set breakpoints,
| | 10:09 | these watch expressions, conditional
breakpoints, if you like, and being able to
| | 10:13 | mouse over these variables and step
through your code will be enough to debug
| | 10:17 | almost any JavaScript you're likely to see.
| | Collapse this transcript |
|
|
8. Building Smarter FormsAccessing form elements| 00:00 | When it comes to working with
forms, we care about several things:
| | 00:04 | first, the values of the individual
form elements, and then the events caused
| | 00:09 | by those form elements when you
change them or when you move in and out of
| | 00:13 | them, and of course the event of
the entire form itself, in particular
| | 00:18 | submitting the form.
| | 00:19 | Now, if you've given your form and
the fields inside it their own IDs, then
| | 00:24 | you can of course use document.getElementByID
to retrieve either the form or any field in the form.
| | 00:32 | And if the HTML for your form has
either an ID or a name property--
| | 00:37 | a name property is quite common with forms--
| | 00:39 | you can use the following format too:
document.forms.name of the form. In this
| | 00:46 | case, it was frmContact.
| | 00:48 | And if you use the name property in
your HTML for your individual form
| | 00:52 | elements, you can use that directly too,
document.forms.name of the form .name of the element.
| | 01:00 | But I'm still a fan of the
good old document.getElementById.
| | 01:05 | So let's talk about the
individual form elements first.
| | 01:08 | Probably the most common one is the
text field, and as we've seen in the Events
| | 01:13 | chapter, text fields have a value property.
| | 01:17 | You can either get it or set it,
and that's the same for a larger text area
| | 01:22 | element if you're using those.
| | 01:24 | Now, we've seen the onfocus and onblur
events, that an element triggers onfocus
| | 01:31 | when you go into it, onblur when you leave it.
| | 01:34 | Now, onblur is always called when
you leave the element, even if you
| | 01:37 | didn't change anything, so there is also an
onchange event if that's more to your liking.
| | 01:42 | But the text fields also generate events
for each keypress, in fact, three events:
| | 01:47 | onkeypress--which is the entire press a
key, then release it--but there are also
| | 01:52 | events for onkeydown and onkeyup,
if you need to get that granular.
| | 01:58 | Now, when it comes to check boxes and
radio buttons, rather than the value
| | 02:03 | property of the text field, which
wouldn't really make sense here, what we care
| | 02:07 | about is the checked property.
| | 02:08 | That's the main, most important
property of the check box element, and
| | 02:12 | that's either going to be true or false.
| | 02:15 | Check boxes and radio buttons also
generate an onclick event when they're clicked
| | 02:20 | on and an onchange event.
Most of the time you can use either or.
| | 02:23 | And what about when you have to say a
select field that contains many options,
| | 02:28 | either showing as a dropdown list or as
a list box itself that you can click in?
| | 02:33 | Well, this can depend.
| | 02:34 | See, in HTML you can have a select
that only allows one selection or a select
| | 02:39 | that allows multiple, and you can
actually read this from the type property of
| | 02:44 | that element, which will either
be select-one or select-multiple.
| | 02:48 | Now, for a single select, when you
select an option of that dropdown list, the
| | 02:54 | onchange event is triggered, and you
can find out which option is selected by
| | 02:59 | reading the.selectedIndex
property of that element.
| | 03:03 | Having said that, but if you have
multiple, that's not enough. What you then
| | 03:07 | have to drill down to is the options
array of that select field and actually go
| | 03:12 | through all its options one by one
and figure out if they have a selected
| | 03:17 | Boolean property for each individual one.
| | 03:20 | That sounds tedious, but it can
really be done in only a few lines of code.
| | 03:25 | But what about the form itself?
| | 03:27 | Sounds like it will be more
complex, but really it isn't.
| | 03:30 | There is one main event of the
form, which is the onsubmit event.
| | 03:35 | This is called when the user clicks--
not surprisingly--the Submit button,
| | 03:38 | whatever has been defined on
the form as the Submit button.
| | 03:41 | Now, by subscribing to this onsubmit
event, we can interrupt it before it
| | 03:47 | actually gets sent to the server.
| | 03:48 | You can check the boundaries of the
fields and even prevent the form from
| | 03:52 | submitting by returning
false from the event handler.
| | 03:57 | So this is a great way we can improve
the client's experience by instantly doing
| | 04:01 | validation on their machine without
waiting for a roundtrip to the server.
| | 04:06 | Now, don't rely on purely
JavaScript to validate any form you have.
| | 04:09 | The assumption here is if you're
submitting information to a server, you should
| | 04:14 | always be performing
validation on the server side too.
| | 04:16 | And let's see a couple of
examples of what we can do with this.
| | Collapse this transcript |
| Preventing a form from being submitted| 00:00 | I have a simple page here with a contact form.
| | 00:04 | If I click the Submit button to send
this, it's actually popping up this
| | 00:08 | message, "Please provide at least an
email address!" and it's stopping me from
| | 00:12 | submitting the form.
| | 00:13 | Let me show you how that's done.
| | 00:16 | The form itself, my HTML, is
nothing particularly special.
| | 00:20 | It's a standard form.
| | 00:22 | It's actually submitting just to a
local page, but normally you would of course
| | 00:25 | be submitting to a server.
| | 00:27 | I am just going to come down towards
the bottom where I have a place, just a
| | 00:33 | span tag with an id of errorMessage,
there is nothing in it right now.
| | 00:38 | Over in my JavaScript, we've got a
couple of simple things going on.
| | 00:42 | Let's talk about the simplest one first.
| | 00:43 | I have a window.onload event.
| | 00:45 | That means when the document
loads call the function called
| | 00:48 | prepareEventHandlers, so we can forget
about the rest of that. This function is called.
| | 00:53 | What it's doing is saying that we
want to handle the onsubmit event of the
| | 00:59 | form called frmContact, and when that onsubmit
event happens we're going to execute this code.
| | 01:05 | It's written in an anonymous function here.
| | 01:08 | That code says, if the email field
is empty, so document.getElementById
| | 01:14 | email.value equal to an empty string,
we're going to set the innerHTML of that
| | 01:21 | error message to, "Please provide an
email address," and the most important thing
| | 01:26 | here to stop the form from
submitting would be return false.
| | 01:30 | In fact, this is really all that I
would need, although for best practice what
| | 01:34 | I'm doing is saying no, if that
wasn't empty, if there was something in the
| | 01:37 | email field, we're going to reset that
message if it did have anything in it and
| | 01:42 | explicitly return true,
| | 01:44 | saying yes, go ahead.
| | 01:46 | So back over, into Firefox, when we
click this without providing an email
| | 01:52 | address, it doesn't submit anything.
| | 01:57 | If I come up here and say test@null.com--
and yes, right now we could really put
| | 02:02 | anything in here--then it
immediately allows me to submit, which is just
| | 02:08 | redirecting to a local page right now,
but the concept is exactly the same, even
| | 02:11 | if you were submitting to
a server-side component.
| | 02:14 | Make no mistake, the single most
important piece of this whole code was this
| | 02:21 | one, that when the
onsubmit calls an eventHandler,
| | 02:25 | we need to either return false to
stop that submit event from going on any
| | 02:29 | further, or return true and say, yes,
I've run the script, just go ahead and do
| | 02:34 | whatever you were going to do anyway.
| | Collapse this transcript |
| Hiding and showing form sections| 00:00 | In this example, rather than react to
the onsubmit of the form, I am actually
| | 00:04 | going to react to an event
of an individual form element--
| | 00:07 | in this case, this check box, that when
I check it is activating or turning on
| | 00:12 | another section of the form itself.
| | 00:15 | This is very, very simple to do.
| | 00:17 | Let me show you the general process
and a few best practices for doing this.
| | 00:21 | So I am going to jump into my
editor. The HTML here is very, very straightforward.
| | 00:28 | The section that has multiple check
boxes in it is wrapped in a div with an
| | 00:32 | id of tourSelection.
| | 00:33 | Now, there are no CSS or other styling
properties being applied to it, so it
| | 00:39 | actually isn't hidden by
default, and that's quite important.
| | 00:42 | We'll talk about that 'why' in a moment.
| | 00:45 | So going into my JavaScript, just a
few simple lines, and getting rid of the
| | 00:50 | last three here, this is just a
window.onload that is calling preparePage.
| | 00:55 | So everything is in this preparePage function.
| | 00:58 | This gets called once, and what we do is here.
| | 01:02 | I'm volunteering to react to the
onclick event of an element called brochures.
| | 01:10 | This is the id of the check box in my HTML.
| | 01:14 | So I'm just saying, when that
gets clicked, we will perform this
| | 01:18 | anonymous function.
| | 01:19 | Of course, the click could be either
checking it in on or checking it off, so
| | 01:24 | the first check is, what is it?
And we don't ask for a value here;
| | 01:29 | I asked for the .checked property of brochures.
| | 01:34 | I don't need to say is it equal to
true or is it equal to false, because
| | 01:39 | the.checked property is a Boolean.
| | 01:42 | So just by putting this in my
condition I'm asking, this is true,
| | 01:45 | I don't need to say if true equals true,
| | 01:47 | it's just, is it true? If it is, what
I'm going to do is grab the div called
| | 01:53 | tourSelection that contains all the
other check boxes, and then--and this is the
| | 01:57 | first time we've seen these properties--
| | 01:59 | I'm using the .style.display property
to drop into basically the CSS of this
| | 02:07 | individual element and change that to block.
| | 02:09 | Now, this is making it visible.
This is the default way that it looks.
| | 02:12 | If it's checked, I want to see it.
| | 02:15 | If there was a change and it wasn't
checked, I am going to set that the same
| | 02:18 | property to none, to hide it.
| | 02:21 | So we've associated this if statement
with the onclick event of the check box.
| | 02:27 | The only other thing that I'm going to
do is because this function gets called
| | 02:30 | once, after I have subscribed to that
event, I'm going to then say, but then go
| | 02:35 | right ahead and hide that div.
| | 02:37 | Now, the reason that I'm doing it here in
my JavaScript is yeah, I could do it in CSS.
| | 02:43 | I could have actually hidden it in the
HTML and CSS, but there's the problem.
| | 02:48 | If somebody went to that page and their
browser had JavaScript disabled, this is
| | 02:54 | a much better way of doing it,
| | 02:55 | what's often referred to as progressive
enhancement, even though this is a simple example.
| | 03:00 | We are using JavaScript to
first enable certain behaviors.
| | 03:05 | If the user doesn't have JavaScript,
everything still works exactly the way it was before.
| | 03:11 | But if they do have JavaScript
enabled, we suddenly have a more
| | 03:15 | interactive form.
| | Collapse this transcript |
|
|
9. UI EnhancementCSS and JavaScript| 00:00 | You should of course already be using
CSS to style your web pages, having a
| | 00:05 | clean division between markup and
presentation, just like we want a clean
| | 00:09 | division between markup and behavior.
| | 00:12 | And the great thing is JavaScript will
allow us to make our presentation and our
| | 00:16 | styles dynamic just like we can make
the actual content on our HTML dynamic.
| | 00:22 | And here's how we do it.
| | 00:23 | The most direct way is that we can set inline
styles on an element directly from JavaScript.
| | 00:30 | Step one, as ever, is to grab the
element using say document.getElementById, and
| | 00:37 | then we use its .style
property to apply a CSS style.
| | 00:41 | And what we're using here are the
same styles we'd use in a CSS document.
| | 00:46 | So, for example, color equals red.
| | 00:50 | And any acceptable value in a CSS file
can be used here in our JavaScript, so we
| | 00:55 | could use, say, hexadecimal colors instead,
| | 00:58 | or myElement.style.left equals 40 pixels
or .style.backgroundRepeat equals repeat-x.
| | 01:06 | Now, one thing to note: you do have
all the usual CSS style properties
| | 01:11 | available, but they might have to be
written a little differently, and here's why.
| | 01:16 | So let's say we take an
example of pure CSS in a CSS file.
| | 01:20 | Well, it's equivalent to set in
JavaScript. It looks kind of similar.
| | 01:25 | We'd say myElement.style.width for
width or myElement.style.color for color.
| | 01:31 | But when it comes to font-weight in CSS,
that becomes fontWeight in JavaScript,
| | 01:38 | with the w capitalized.
| | 01:40 | Same thing with background-color.
| | 01:42 | So anything that would be written
with a dash or hyphen in CSS becomes
| | 01:47 | camelCased in JavaScript.
| | 01:49 | You remove the dash and any
subsequent word becomes capitalized.
| | 01:52 | Now, this is not JavaScript just being
different for the sake of it. Think about it.
| | 01:57 | We can't put a dash in our code.
| | 02:00 | That's how we subtract in JavaScript.
| | 02:03 | And because there doesn't need to
be white space between our operators,
| | 02:06 | JavaScript here would think we're
trying to perform a subtraction.
| | 02:10 | myElement.style.background-color or
font-weight just wouldn't work, so we do camelCase.
| | 02:18 | Now, when you're setting these
properties, you always set them as a string.
| | 02:23 | And if they need units when written in
CSS, you pass units in JavaScript, so
| | 02:27 | notice that we have the
width is equal to px for pixels.
| | 02:32 | We need the leading hash, or
leading pound sign if you'd prefer, for
| | 02:35 | the hexadecimal colors.
| | 02:36 | And one thing to take care of, if
you're used to writing a lot of CSS and it's
| | 02:42 | second nature to right say 230 px;,
| | 02:46 | you don't want to put that semicolon
inside the double quotes that you're
| | 02:50 | setting the property to.
| | 02:51 | Yeah, sure, we use the semicolon in
JavaScript, but it's outside the quotes,
| | 02:56 | to end the statement.
| | 02:57 | Now, if you have predefined classes in
your CSS file and you'd like to just use
| | 03:02 | JavaScript to apply an entire class
to an element, we can do that too.
| | 03:06 | So we had myElement.style and we can
think we might have myElement.class,
| | 03:11 | but here's the problem.
| | 03:12 | It's not just the word class.
You see, class is a special name in most
| | 03:18 | programming languages.
| | 03:19 | It has to do with object orientation.
| | 03:20 | And even though we don't use
the word class in JavaScript,
| | 03:23 | it is a reserved word,
and you're not allowed to use it.
| | 03:27 | So the property we actually set is className.
| | 03:31 | Grab the element and set its .className
property to whatever the name of your
| | 03:36 | class is in your CSS file.
| | 03:38 | If you need to clear it, you can actually
clear just by setting it equal to an empty string.
| | 03:44 | So let's see a couple of examples.
| | Collapse this transcript |
| Removing and applying CSS classes| 00:00 | If you have a class defined in
your CSS file, such as this one
| | 00:04 | called.example, it's very easy to make
this apply to a particular element in
| | 00:10 | JavaScript; in fact, you'll spend
more code saying when you want this to
| | 00:14 | happen than actually doing it.
| | 00:16 | If I look at some example of JavaScript,
I have to apply this class called example.
| | 00:21 | This is the only code that
I actually need to write.
| | 00:26 | Find the element, .className, =example.
| | 00:32 | The only code that I'm wrapping
around it here, not surprisingly, is being
| | 00:36 | called when the document loads and
just so I can have a bit of interactivity,
| | 00:41 | I am going to respond to an onclick
event on the div called mainContent.
| | 00:45 | I am going to execute this anonymous
function that actually asks, what is that
| | 00:52 | class? Is that class currently set to example?
| | 00:54 | If it is, I am going to blank it out.
| | 00:57 | If it isn't, I am going to set it to example.
| | 00:59 | So you've just got a little
toggle on/off here happening.
| | 01:03 | If I jump over and just open that up in
the browser, right now that class is not
| | 01:09 | being applied, but if I click anywhere
in this main div, we're applying that
| | 01:14 | class, which is actually setting this
part of text to white, and just clicking
| | 01:19 | back and forth. It's either
applying the class or taking it off.
| | 01:23 | Now, one thing to note, you can apply a
class all you want, but it's still using
| | 01:28 | the cascading rules of CSS, which means
if there are more specific rules being
| | 01:34 | applied to some of this content, say
through ids or even inline styles, the
| | 01:40 | closer ones are going to win.
| | 01:42 | So in this case what it looks like
we're doing is we are being successful in
| | 01:47 | applying the color--white--to the
headline, but it looks like the paragraph
| | 01:52 | probably has its own color
being set a little closer to it.
| | 01:56 | It doesn't look like font-size is making any
difference, although we do have 1em there.
| | 02:00 | Text-align right certainly
looks like its being applied.
| | 02:04 | Again, this all comes down to normal CSS rules.
| | 02:08 | JavaScript applying a class is pretty
much the same as manually applying that
| | 02:12 | class in your HTML when the page loads.
| | Collapse this transcript |
| Changing inline styles| 00:00 | So I'm going do something a bit more
interesting to this page, using inline styles.
| | 00:05 | Let's say we're trying to get
people to sign up for our newsletter.
| | 00:09 | The page itself is pretty normal.
| | 00:12 | I do have a section of it that's
been defined as a div with an ID of join,
| | 00:17 | which is trying to get people to
sign up for the monthly newsletter.
| | 00:21 | Well, what I'm going to do is a little bit of
JavaScript to make this stand out a bit more.
| | 00:25 | I'm going to jump over into my JavaScript file.
| | 00:28 | Let's get rid of the easy code.
| | 00:31 | Down at the bottom, I have a window.onload
| | 00:34 | that's going to call a setTimeout
function that passes in beginAnimate, 5000.
| | 00:39 | That simply means do a single call to
the beginAnimate function in five seconds
| | 00:46 | after the page is loaded. What does that do?
| | 00:49 | Well, up here in beginAnimate what I'm
doing is I've got three lines that all
| | 00:54 | grab that actual div, which
currently is part of the body of the page.
| | 00:58 | What I'm going to do is a
couple of CSS style tricks.
| | 01:01 | I'm going to set its position to
absolute, then its left position to 0 pixels,
| | 01:07 | and its top position to 100
pixels from the top. Well, then what?
| | 01:12 | I'm now going to call setInterval,
and this is the repeating timer event that's
| | 01:18 | going to call the animateBox
function about 20 times a second.
| | 01:24 | And if you remember, setInterval gives
you back a variable, it gives you back a
| | 01:28 | handle to that interval, which I'm just
going to store in intervalHandle, which
| | 01:32 | is defined as a global variable up here.
| | 01:36 | So, really all the work is happening
in this function called animateBox.
| | 01:41 | First thing it does is say, whatever the
current position is I'm going to add 5 to it.
| | 01:45 | In fact, the first time this ever gets called
current position will be 0. So we add 5 to it.
| | 01:52 | I then grab that div and set its
style.left property to whatever the current
| | 01:59 | position is, and then I'm going to use
the plus sign and add px, remembering
| | 02:03 | that we have to pass in any units that are
used by that CSS style--in this case, pixels.
| | 02:10 | Now, currentPos is actually a number,
but px is a string, so it will concatenate
| | 02:16 | these together as a string.
| | 02:17 | So it will be 5 px, 10 px, 200 px, and so on.
| | 02:22 | And all that I'm doing here is saying,
if the current position, the leftmost
| | 02:27 | position, gets to be greater than 900--
and bear in mind what I'm checking here
| | 02:32 | is just the number variable
without the px, that's fine--
| | 02:36 | I'm going to clear the interval, and it
makes it so that this function doesn't
| | 02:40 | get called anymore, and then I'm going
to reset the div to its original styles.
| | 02:45 | Really, I'm just going to pull off any
custom styles that I applied up here in
| | 02:50 | the beginAnimate section.
| | 02:52 | Not an awful lot of code,
and let's see what impact it has.
| | 02:57 | I'll jump back over and
I'll just open up this page.
| | 02:59 | Well, after a few seconds what's going
to happen is our little thing that we're
| | 03:04 | trying to push is going to pop
over and make itself rather annoying.
| | 03:10 | And yes, indeed, we're using our
powers of JavaScript for evil here.
| | 03:14 | If you note that after it crosses the
screen, it has actually jumped right back
| | 03:18 | down to the bottom here,
just as it normally was.
| | 03:21 | And I don't recommend
doing this on a regular site;
| | 03:24 | you're just going to annoy people.
But I think it's a pretty good example of in
| | 03:29 | just a few lines of code that you can
really significantly manipulate some of
| | 03:36 | the content that you have on your page,
and using the ability for JavaScript to
| | 03:41 | talk to CSS, even in just a few simple
properties, can be very powerful indeed.
| | Collapse this transcript |
|
|
10. JavaScript Best PracticesUnderstanding JavaScript style| 00:00 | When we talk about style with
programming languages, we're moving away from the
| | 00:04 | rules of how you must and must not
write JavaScript into more of how you should
| | 00:10 | and shouldn't write it.
| | 00:11 | So how should you name your variables,
where should you put your braces, what
| | 00:15 | should you call your functions,
and where should they be placed in your code?
| | 00:20 | Because this matters.
| | 00:22 | Style decisions matter for you and
for other developers on your team.
| | 00:26 | You want your code to be readable,
you want it to be consistent,
| | 00:29 | and you also kind of need to play along
with how everyone else in the world is
| | 00:33 | writing their JavaScript, because
that's going to make it easier to read
| | 00:36 | example code and read books and, more
importantly, recognize whether that code is written well.
| | 00:42 | And style matters simply because
JavaScript is the most publicly viewable
| | 00:47 | programming language in the world.
| | 00:49 | Unlike a desktop application, with
JavaScript running on a web page, all your
| | 00:53 | code is sent to whoever requests it.
| | 00:56 | Every client's browser gets a copy of
your JavaScript in plain readable text.
| | 01:01 | Sure, most people won't look at it,
but they could. They can view source.
| | 01:05 | They can use tools like Firebug to get
to it. Other web developers can see how you write your code.
| | 01:10 | So think of all the JavaScript you
write as effectively being published on the
| | 01:15 | web and get into good habits early.
| | 01:18 | So what are these good habits?
Well, let's begin with some naming conventions.
| | 01:21 | We get to choose names for
variables, functions, even objects, if you
| | 01:26 | define your own objects.
| | 01:27 | Now, the rules of JavaScript say you
must use letters, numbers, dollar sign, and
| | 01:32 | underscore, and you can't start with
a number, but that doesn't mean that
| | 01:36 | something like this would be a good
name for a variable. We want clarity.
| | 01:41 | We want readability. We want meaning.
| | 01:44 | Yes, okay, when we're learning,
we use placeholder names a lot:
| | 01:48 | var a, var b, var c, x is a pretty common one,
or common meaningless words like foo or bar.
| | 01:57 | But our real JavaScript variables
will represent meaningful information:
| | 02:02 | the name in a textbox, a date, the
height and width of an image, or a collection
| | 02:06 | of element nodes that
represent the links in a menu.
| | 02:08 | So naming conventions have developed
over the years, and these days the dominant
| | 02:14 | way JavaScript is written is this.
| | 02:16 | Variables and functions, which will
be most of what you name yourself, are
| | 02:20 | written in camelCase.
| | 02:22 | The word would start lowercase.
| | 02:24 | If it's just one world like score,
it would be all lowercase. But with
| | 02:28 | multiple words you capitalize the
first letter of each subsequent word, like
| | 02:33 | the hump of a camel.
| | 02:35 | Multiple words are not separated with
underscores as they might be in some other
| | 02:39 | programming language.
| | 02:41 | Functions are named the same way,
or methods if they're in an object.
| | 02:45 | Now, these are typically multiple words for
clarity and often in a loose verb noun format.
| | 02:52 | Think of the way that we work with the DOM:
| | 02:54 | createElement, appendChild, getElementById.
| | 03:01 | When we're working with objects, the
convention here is to also capitalize the first word.
| | 03:07 | And quite often objects only aren't
one word. Think of the way we've seen
| | 03:10 | objects in JavaScript, like the Math
object and the Date object and the Array object.
| | 03:15 | Now, bear in mind, we still use
camelCase too. After all you create a variable
| | 03:21 | that uses camelCase that's based on an
object that capitalizes the first letter.
| | 03:27 | Now, if you're coming from a
language that uses underscores a lot, or
| | 03:32 | prefixes variables with an abbreviation
that's meant to represent the type of information,
| | 03:37 | you can argue against
camelCase as much as you like.
| | 03:40 | There is nothing stopping you from
using your favorite naming style, but
| | 03:44 | camelCase is the dominant style for JavaScript.
| | 03:47 | It is what's recommended by the Yahoo!
| | 03:49 | style guidelines, by the
Google style guidelines.
| | 03:52 | It's what's used by the popular
JavaScript libraries, like jQuery and Prototype,
| | 03:57 | and of course it's what's used by
the DOM methods themselves. There is no
| | 04:01 | escaping camelCase in JavaScript.
| | 04:04 | Let's talk about brace style, where to
put the opening and closing curly braces.
| | 04:08 | The dominant style in JavaScript is the most
traditional brace style for C-based languages.
| | 04:13 | If you have an if statement or a while
loop, the curly brace opens on the same
| | 04:18 | line as the keyword, as the
if or the while or the for.
| | 04:22 | The code is indented inside the block,
and the closing curly brace is on a line by itself.
| | 04:27 | If you're adding an else to a if
statement, you'll typically see that continued
| | 04:31 | on the same line, again, with the
opening curly brace of the next section on the
| | 04:35 | same line as the keyword.
| | 04:37 | Now, there are other ways, like Pascal
or Allman style, when the opening braces
| | 04:42 | on its own line and lines up with the closing
brace, but I avoid this style in JavaScript.
| | 04:48 | Now, while it wouldn't matter in most
languages, in JavaScript you can run into
| | 04:52 | a situation with JavaScript's own
ability to insert what it thinks are missing
| | 04:56 | semicolons on lines that don't have them.
| | 04:58 | It's a rare issue, so I'm not going to
get into specifics, but if I use the style
| | 05:02 | on the left, I don't have to
worry, and it is the standard style.
| | 05:06 | So for all your ifs, your whiles,
your functions, all of these constructs,
| | 05:11 | open the curly brace on the same line as the
keyword, the while, the for, or the function.
| | 05:17 | And while we're talking about blocks of
code, as in other C-based languages, if
| | 05:22 | you have say an if statement that
only does one thing, you can technically
| | 05:27 | remove the curly braces.
| | 05:29 | If there is one statement after the if
and the condition, it behaves as if there
| | 05:34 | are curly braces around it.
| | 05:36 | But, as in other C-based languages,
it's a really bad idea to do this, because
| | 05:40 | later on it's super easy to
add a line of code to this.
| | 05:45 | And when you read this code what you
think you're getting is this kind of block,
| | 05:50 | where if x is more than 500 we're
going to execute these two lines, but if we
| | 05:54 | left the braces off, what
we're actually getting is this.
| | 05:59 | If the condition is true, we will pop
up the alert and we will always then go
| | 06:03 | ahead and reset everything.
And these kind of bugs can be a real pain to
| | 06:08 | recognize, so always use the curly
braces, even for one-line blocks.
| | 06:13 | Now, another general rule here is
even though you don't have to define your
| | 06:18 | functions before you call them--so,
for example, here I've got one function
| | 06:23 | called some function that called other
function, and other function is nicely
| | 06:27 | defined after it in our code file--
the preference and the best practice is to
| | 06:32 | define your functions before they are called.
| | 06:35 | In some languages you have to do this.
In JavaScript you don't have to, but it
| | 06:39 | does make for more
readable and more usable code.
| | 06:42 | So to review, we can really
keep a few simple rules in mind:
| | 06:46 | Use camelCase for variables,
functions, and methods, and this will be the
| | 06:49 | majority of what you have to name yourself.
| | 06:53 | Open curly braces on the
same line as the keyword.
| | 06:55 | Always use blocks, even
if there's only one line.
| | 06:59 | Define your functions before you call them.
| | 07:01 | And a couple of things we've
been talking about along the way:
| | 07:04 | always use semicolons to end a
statement--even if you might not have to, you
| | 07:09 | should--and always use var
when declaring a variable.
| | 07:14 | We could go deeper than this with style,
but that's enough to get us started.
| | 07:17 | If you do want to go deeper and
more formal, do a search for the phrase
| | 07:20 | 'javascript style guidelines' and you'll
find some really good documentation that
| | 07:24 | have been created by the
JavaScript developers at places like Yahoo!
| | 07:28 | and Google and Mozilla.
| | 07:30 | Now, I don't have a personal favorite,
but if you're after something more
| | 07:33 | formal, just take a look at these and
be consistent about the way you write
| | 07:38 | your code.
| | Collapse this transcript |
| Minifying your code| 00:00 | If you have ever looked at the source
of a web page, you might have seen some
| | 00:03 | code that looks like this, all
squeezed together and essentially unreadable.
| | 00:08 | Now this is actually JavaScript here,
but that doesn't mean somebody wrote it this way.
| | 00:13 | This is the result of
minification; the code has been minified.
| | 00:17 | This is a process to go through some
regular JavaScript and minimize it to compact it.
| | 00:23 | We would first start by removing
comments. Then we might rename long variable
| | 00:28 | names and function names to shorter names,
| | 00:31 | then get a little line breaks, and start to
combine multiple statements onto one line.
| | 00:36 | Now, minification is done for one reason,
to decrease the size of the JavaScript.
| | 00:44 | The reason that you do it is to
improve page load times, because the script
| | 00:49 | gets downloaded faster.
| | 00:50 | The two things minification is not:
This is not compiling your JavaScript into a
| | 00:55 | machine code, or anything like that.
| | 00:57 | It is functionally identical.
| | 00:59 | It's just a smaller amount of characters.
| | 01:02 | And number two, it's not
intentionally scrambling it.
| | 01:05 | Yes, minified code is ugly, and it's
tougher to read, but that's not why we do it.
| | 01:09 | It's not for what's called obfuscation.
| | 01:11 | Now the question is, how do you do this?
| | 01:14 | Well, you could do it yourself obviously,
but that would be very, very tedious,
| | 01:17 | so there are lot of minification tools
for JavaScript out there. Some of the
| | 01:22 | better knowns are JSMin, the Yahoo UI
Compressor, and Google Closure Compiler.
| | 01:29 | Now many of these are command line tool.
They are actually written in C or in Java.
| | 01:33 | You can just download them and
run them from the command line.
| | 01:36 | Well, there are a couple that can
be accessed over the web, like the
| | 01:39 | Google's Closure Compiler.
| | 01:40 | Let's take a look at that one.
| | 01:42 | Google's Closure Compiler can be
downloaded so you have your own copy, but
| | 01:46 | there's a version available on the
web, at closure-compiler.appspot.com.
| | 01:52 | What I really need to do is to grab
some JavaScript of mine to minify.
| | 01:56 | Well, I have some just
sitting in my editor here.
| | 01:59 | I'm just going to select all of it,
jump back over into Closure Compiler,
| | 02:05 | and paste it in there.
| | 02:06 | So it's regular JavaScript.
| | 02:08 | There is nothing particularly special
about it. And I am just going to go ahead,
| | 02:11 | leave all the settings as is, and hit
Compile. And over here on the right-hand
| | 02:17 | side I can see that it's actually
shrunk it a bit. The original size was 1.12K,
| | 02:23 | and the compiled one is 595 bytes.
| | 02:26 | Okay, we are not really starting off
with a big file, but you can see the point
| | 02:30 | of what's happening. The comments have
been stripped out, some of the whitespace
| | 02:33 | is gone, and it seems that we've
done a little bit of tweaking here.
| | 02:38 | However, we can take this a little bit
further down. Over on the left-hand side
| | 02:41 | I can choose to do an advanced setting
for the Closure Compiler, hit Compile
| | 02:46 | again, and that shrinks it
down even further, to 479 bytes.
| | 02:51 | Now in fact, Google's Closure
Compiler is not just a strict minifier.
| | 02:56 | It does have a few abilities inside it
to detect code that might not be called.
| | 03:01 | So it's definitely an interesting one to
run your code through, because it tries
| | 03:04 | to do some optimization and
not just minification here.
| | 03:08 | But that's mainly what I'm interested in
it for. So I could either grab this and
| | 03:13 | just copy and paste it, although if you
see, it's also giving me a copy of a file
| | 03:17 | which I could actually just
download here at the default.js link.
| | 03:22 | Because the whole reason is that we
as developers need the comments, we
| | 03:26 | need that whitespace.
| | 03:27 | We need the meaningful variable names.
| | 03:29 | The browser doesn't need it in order to run it.
| | 03:32 | It's quite happy with the
compacted version over here.
| | 03:35 | So two things with minification:
| | 03:37 | You only do this when you're happy that
your script is correct, you pretty much
| | 03:41 | only minifiy at the end.
| | 03:43 | And two, of course, you keep a copy of
the original for when you need to change it,
| | 03:48 | because while you can unminify to an
extent--you can get some white space back--
| | 03:53 | there is no way to get back a comment
| | 03:54 | that doesn't exist anymore, or know what a
renamed variable was originally called.
| | 04:00 | Now as we will start to see a
little later on, it's very common to find
| | 04:04 | third-party JavaScript libraries
available to download in both the minified
| | 04:09 | format, such as here jQuery, that when
it's minified and zipped, it's 31K,
| | 04:14 | whereas, the regular version is 229K.
| | 04:17 | You would end up using the minified
one on your site to make for a quick
| | 04:21 | download, but you can always
download and view the non-minified one if you
| | 04:25 | want to read the code.
| | Collapse this transcript |
| Using JavaScript code checkers| 00:00 | Just as we can run our JavaScript
through a separate program to minify it, we
| | 00:04 | can also run it through another
program to check its quality, and to check it
| | 00:08 | for common problems.
| | 00:10 | Now in contrast to minification where
there are many different tools to choose
| | 00:14 | from, there is one best known
JavaScript code quality checker, which is JSLint
| | 00:19 | by Douglas Crockford, whose the
JavaScript architect at Yahoo!
| | 00:23 | You can find this at jslint.com.
| | 00:26 | With this what you can do is take some
code--I have got a block of JavaScript
| | 00:29 | here--I'm just going to copy, take it
over the JSLint, paste it in there, and
| | 00:34 | click this button that says JSLint, to check it.
| | 00:38 | Now, when you do this it's
going to complain about a lot.
| | 00:41 | JSLint will point out every little
thing you do that isn't perfect, from the
| | 00:46 | amount of whitespace you use between
your operators, to how many characters
| | 00:50 | you indent your code, to whether you
declare all your variables using var,
| | 00:54 | whether you are declaring your functions
before you use them, and a thousand other things.
| | 00:58 | I can see that just with this little amount of
code I have got a whole bunch of problems here.
| | 01:03 | Now these errors have nothing to do with
whether or not your code actually works.
| | 01:08 | It might work just fine and JSLint will
still complain about a hundred different
| | 01:12 | things in 10 lines of code.
| | 01:14 | This is quite similar that if you take
a web page that you know works perfectly
| | 01:17 | well and run it through a formal HTML
and CSS validator, you're typically going
| | 01:22 | to find a bunch of things
that technically aren't valid.
| | 01:25 | It's kind of the same thing here.
And as with HTML and CSS validation, if you
| | 01:30 | take the time and fix all those little
things, it will make your code better,
| | 01:34 | but there are a couple of
features to be aware of,
| | 01:36 | so to not get frustrated.
| | 01:38 | First off, we look at these errors,
but we start at the top and work down.
| | 01:43 | You don't pick and choose ones here.
| | 01:44 | So we are starting off, problem at line 9
character five, missing use strict statement.
| | 01:50 | Now this is an interesting one.
| | 01:52 | In ECMAScript edition 5 there
is something called Strict mode.
| | 01:56 | It's an instruction to the browser to
not even allow sloppy JavaScript.
| | 02:00 | It requires the use of var for variables.
| | 02:03 | And JSLint wants us to use
Strict mode, even if we are just
| | 02:07 | writing ECMAScript 3.
| | 02:09 | Now I could do this in a couple of ways.
If I actually added inside my functions
| | 02:14 | just a line, say here,
| | 02:18 | that was "use strict" inside double
quotes, and just ended with a semicolon.
| | 02:24 | It looks little strange here because we
are just putting in a string, and that's
| | 02:27 | intentional, because ECMAScript 3
doesn't really understand this, and all it's
| | 02:31 | going to see here is a
string literal and just ignore it.
| | 02:34 | But the very up-to-date browsers
actually do recognize this as trying to
| | 02:38 | enforce Strict mode.
| | 02:40 | However, if I click JSLint, what I
will see is okay, our first error is gone,
| | 02:45 | but if I go down a little bit,
I'll probably find it somewhere else.
| | 02:49 | There we go, Missing 'use
strict' statement, if I didn't add that
| | 02:52 | to all my functions.
| | 02:54 | Well, if I know what it's complaining
about, what I can do is come down towards
| | 02:59 | the bottom of JSLint and here I find a
whole bunch of options that I can check
| | 03:04 | to allow JSLint to tolerate certain things.
| | 03:08 | And one of them is the Tolerate
missing 'use strict' pragma that use
| | 03:13 | strict instruction.
| | 03:14 | So I am going to check
that and click JSLint again.
| | 03:19 | I still have some errors here. The next one,
| | 03:22 | Problem at line 10 character 5:
| | 03:23 | 'document' was used before it was
defined, and then it complains that the line
| | 03:28 | is a document.getElementById.
| | 03:31 | Well, this is pretty common stuff.
| | 03:33 | The reason that it's actually doing
it here is, as you know, JavaScript was
| | 03:37 | intended for the browser, but isn't
always just used in the browser, and the
| | 03:41 | document object only makes sense if
we know that we're in a browser.
| | 03:46 | So back down to the Options, and I'm
checking the one on the left here that
| | 03:50 | says Assume a browser.
| | 03:52 | We run JSLint again.
| | 03:54 | We've gotten passed that issue,
but we still got problems.
| | 03:57 | This next one here,
Expected 'intervalHandle' at column 5, not column 1.
| | 04:02 | Well, what does that mean?
| | 04:03 | Here it's literally just complaining
about the correct level of indentation.
| | 04:08 | If you see that this line beginning
intervalHandle equals is inside our
| | 04:12 | function, but it's not indented
the same way that the rest are.
| | 04:15 | It should be indented with four spaces.
| | 04:18 | That's what JSLint likes.
| | 04:20 | So if I do that, we run
JSLint again, and we go on.
| | 04:24 | Now quite similar to that, what you'll
see is there is a lot of complaints here,
| | 04:28 | missing space between comma and number.
| | 04:31 | It likes us to leave a space
after the comma between parameters.
| | 04:35 | Again, we don't have to.
| | 04:37 | This is not going to change how the
code works, but it's got its own set of
| | 04:40 | presentational rules.
| | 04:43 | Missing space between current
position and the plus equal sign. What it's
| | 04:49 | complaining about there are, for example,
things like this line here, where it
| | 04:54 | lacks a single space around the operators.
| | 04:58 | Now what you'll often find is that
JSLint will complain about a lot of this, so
| | 05:02 | one of the other options I could do,
if I don't want to fix everything right
| | 05:05 | now, is I could allow it to
tolerate messy whitespace.
| | 05:10 | So I am going to go back and run it again.
| | 05:12 | Well, we are getting smaller here.
| | 05:14 | Problem at line 13 character 34,
animate box was used before it was defined.
| | 05:20 | What does that mean?
| | 05:21 | Well, we are calling this
setInterval function passing in animateBox.
| | 05:28 | The issue is is the function animateBox
isn't defined to later on in the code.
| | 05:32 | Again, while this will work, best
practices say that our function should be
| | 05:36 | defined before we write code that use them.
| | 05:40 | So this function animateBox should be
defined before I use it in an argument.
| | 05:44 | So what I am going to do is cut the
entire function, and I just take it up and
| | 05:51 | paste it in here, and then we run
JSLint again, and we're getting okay
| | 05:56 | there, we are getting down.
| | 05:57 | Next one, it's saying,
Type confusion, number and string, and the line it's
| | 06:02 | complaining about is this, where we are
actually concatenating a number, which
| | 06:06 | is current position, and the string px.
| | 06:08 | Well, in fact, I know this is okay.
| | 06:10 | This is what I want to do.
| | 06:11 | I am actually trying to create a
string that says 200 PX or 300 PX,
| | 06:17 | so I am absolutely fine that that happens.
| | 06:20 | So I need to also go and tell it
down here to tolerate type confusion.
| | 06:28 | JSLint. I could just ignore that as well.
And now finally, we have something here
| | 06:32 | Problem at line 21, character 9:
| | 06:34 | something was used before it was
defined, and this I just added so we could
| | 06:38 | actually see a problem here.
| | 06:40 | And the problem is that I just start
using a variable, something = something +1.
| | 06:45 | Well, this should really have been
defined somewhere else with the term var, but
| | 06:49 | it hasn't been defined probably.
| | 06:51 | So I could either delete the line
that says something = something + 1, or I
| | 06:56 | could go and define the variable up
towards the top, so it's accessible there, or
| | 07:01 | even somewhere else in the function.
| | 07:04 | And then we have no errors. But as
you can see, JSLint will always complain
| | 07:09 | about your code, so try not to be too
upset when it complains about every single line
| | 07:13 | that you've written.
| | 07:14 | It is very picky indeed.
| | 07:16 | It's supposed to be picky.
| | 07:17 | That's what JSLint is designed to do.
| | 07:20 | But as you become comfortable with
JavaScript, it's a really good exercise to
| | 07:24 | make the effort to understand what it's
complaining about, even as--what I did, I
| | 07:30 | kind of ignored a of few of those errors
and told it to be tolerated, at least I
| | 07:34 | understood what its problem was.
| | Collapse this transcript |
|
|
11. JavaScript LibrariesIntroduction to JavaScript libraries| 00:00 | JavaScript is a small language.
| | 00:02 | We really have covered most of it already.
| | 00:05 | But unlike technologies like Java or
.NET or Cocoa, it doesn't have dozens of
| | 00:10 | built-in libraries with
thousands of objects for us to use.
| | 00:13 | So we are now at the point where we need to
start thinking about writing a bunch of code.
| | 00:18 | But you know the things that we want to
do with JavaScript are probably not all
| | 00:22 | that different from what other people have
wanted to do with JavaScript over the years.
| | 00:27 | And the great thing is some of those
people already wrote a lot of the code
| | 00:31 | you need and bundled it together into the
form of one of many JavaScript libraries.
| | 00:37 | Now a JavaScript library simply means a
bunch of JavaScript somebody else wrote
| | 00:43 | so you don't have to.
| | 00:45 | So what are these libraries?
| | 00:46 | There are dozens of them.
Here's just a few.
| | 00:49 | Some of these libraries, like Google's
Closure Library or MooTools or the Yahoo!
| | 00:55 | YUI Library, are considered
general-purpose JavaScript libraries.
| | 01:00 | They have a whole lot of functions
that help with navigating through the DOM.
| | 01:04 | They include code for cross-browser
detection, so it's easier to work with
| | 01:08 | events without worrying about which version
of Internet Explorer your user might have,
| | 01:13 | or working with animation. They make
it easy to have your JavaScript request
| | 01:17 | information from a web server, then
update the page when it gets a response,
| | 01:21 | something often referred to as AJAX.
| | 01:23 | To use any of these libraries, I
just simply go there and download it.
| | 01:28 | jQuery here, for example, gives me an
option of choosing the minified version or
| | 01:33 | the full development one.
| | 01:34 | It is just JavaScript.
| | 01:36 | You just download it and link to it the
same way you'd link to a file of your own code.
| | 01:41 | It is just JavaScript, so
technically you're not getting anything you
| | 01:44 | couldn't have written yourself, but it might
have taken your months to write all this stuff.
| | 01:50 | Now on the other hand, some JavaScript
libraries are more specialized. Rather
| | 01:55 | than be general purpose, things like
Lightbox are simply JavaScript libraries
| | 01:59 | for popping up images on your web site.
| | 02:02 | You've probably seen these ones before.
| | 02:05 | They might be for slideshows.
| | 02:07 | They might be for implementing things like
drag-and-drop and working with accordions.
| | 02:13 | They could be as simple as a library that
just helps you add curved corners to your divs.
| | 02:19 | Now most of these libraries are
open source and they are free.
| | 02:23 | There is no licensing.
| | 02:24 | You simply grab the code and use
it, do whatever you want with it.
| | 02:28 | So I encourage you to explore
what's available, and new ones are
| | 02:31 | appearing all the time.
| | 02:33 | Now if you go back a few years, there
was a lot of competition between the
| | 02:37 | different libraries, but a
clear winner did emerge.
| | 02:41 | And the most popular general purpose
JavaScript Library, by a mile, is jQuery.
| | 02:46 | We are going to talk about this one shortly.
| | 02:48 | Now I occasionally have people ask
if they should avoid these libraries
| | 02:53 | and whether real JavaScript
programmers, whatever that means, write
| | 02:56 | everything themselves.
| | 02:57 | And the answer is absolutely not.
| | 02:59 | Knowing the JavaScript libraries,
particularly jQuery, is a core skill for a
| | 03:04 | JavaScript developer these days.
| | 03:06 | It's part of the landscape, and as
soon as you've gotten a basic knowledge of
| | 03:10 | JavaScript, like the one we have got so far,
you'll want to start exploring these libraries.
| | 03:14 | They really will make your life easier.
| | Collapse this transcript |
| Linking to multiple JavaScript files| 00:00 | So I have suggested that your default
way of including JavaScript on your page
| | 00:05 | is to have a script tag right before
the closing body tag that just links to a
| | 00:09 | separate JavaScript file.
| | 00:10 | And it is also quite common to see
several script tags here, and particularly
| | 00:15 | common when it comes to having both
your own code and one or more JavaScript
| | 00:19 | libraries and perhaps a link to a
Google Analytics JavaScript and so on.
| | 00:23 | But two things to keep in mind:
| | 00:25 | you want to keep the amount of script
tags here at a minimum, and the order of
| | 00:30 | them matters. So, why minimum?
| | 00:33 | Well, just be aware that every
JavaScript file you link to is a separate request
| | 00:38 | the browser needs to make to the web server.
| | 00:40 | The browser gets the HTML
and moves down through it.
| | 00:44 | It sees the link to the JavaScript
and makes a call to the server for that
| | 00:48 | first JavaScript file.
| | 00:49 | It then waits for that file to finish
downloading, and then, and only then, moves
| | 00:55 | on to the next one, calls the web
server for that file, and waits again.
| | 01:01 | And that order continues.
| | 01:03 | It doesn't download the
JavaScript simultaneously.
| | 01:06 | It will do it sequentially.
| | 01:08 | And that means the more files you have
the more requests the browser needs to
| | 01:12 | make and the slower your page is going to load.
| | 01:17 | So while you might find it easy when
writing JavaScript to have multiple small
| | 01:21 | files, it's definitely worse for the user.
| | 01:24 | So combine your JavaScript where you can.
| | 01:27 | You should have as few
JavaScript files as possible.
| | 01:31 | And secondly, the order
of the script tags matters.
| | 01:35 | If you have a file of JavaScript that
inside it calls a function in a second
| | 01:40 | JavaScript file, well, you want to make
sure to load that file before the code
| | 01:44 | that tries to call this.
| | 01:45 | This is very common with libraries.
| | 01:47 | If you're using, for example, the jQuery
library, you want to make sure that you
| | 01:51 | load jQuery first before any
JavaScript that might actually try to use jQuery,
| | 01:57 | and the same goes for any other dependency.
| | 01:59 | So sure, you can't always get this
down to just one file, but you should
| | 02:04 | certainly be very careful if you see
this growing to seven or a dozen, and see if
| | 02:08 | you can't combine some of them together.
| | Collapse this transcript |
| Introduction to jQuery| 00:00 | jQuery is the most popular
JavaScript library by far, and it really does
| | 00:05 | make JavaScript easier:
| | 00:07 | easier to navigate and manipulate the
DOM, easier to add events, easier to
| | 00:11 | work with animation, and really to do
the same things we have been doing all
| | 00:14 | along but with less code.
| | 00:16 | So how do you use it?
| | 00:17 | Well, very simply, what you need to
do is go out to jquery.com and just
| | 00:23 | download the JavaScript.
| | 00:25 | You will find that even from the
homepage you have a choice of either the
| | 00:28 | development version, which is just
the fully readable JavaScript, or a
| | 00:32 | production version, which is 31k
after its been minified and gzipped, so it
| | 00:38 | really doesn't add much weight to your web site.
| | 00:39 | I have actually gone ahead and
downloaded both versions to the current folder
| | 00:46 | that I am working with,
but I only need the minified one.
| | 00:49 | I have no intention of changing or
even reading the other code. And then if I
| | 00:54 | want to use it in my HTML page, I'm
simply going to go in and add a link to it.
| | 01:02 | In this case, I'm linking
to the minified version.
| | 01:05 | Now you could certainly make an
argument here that it's possible to load jQuery,
| | 01:09 | or any other library, with the script
tag up in the head of your document. And if
| | 01:14 | I thought I needed it as soon as
possible, I might do that, but I'm pretty
| | 01:19 | confident that I can load it down here
just fine, though I am making sure that I
| | 01:23 | am loading the jQuery file before
any of my own code that might use it.
| | 01:29 | So what do we then do with it?
| | 01:30 | Now let's start with something simple.
| | 01:32 | Without jQuery, we'd often
write lines of code like this:
| | 01:37 | document.getElementById, give it the
name of an ID from the HTML, and then work
| | 01:42 | with methods, or in this case a property.
| | 01:44 | I am setting the className= "highlight."
| | 01:47 | With jQuery, I might write this instead:
| | 01:50 | The word jQuery with a lowercase J
and an uppercase Q. In the parentheses
| | 01:56 | here, I'm using the number sign or
pound sign or hash sign, depending on which
| | 02:01 | country you're from, and then
myDiv to indicate that this is an ID.
| | 02:06 | This is the same way we do this in CSS,
and then a dot and then addClass (" highlight").
| | 02:12 | So you might think well, so what?
| | 02:13 | A little less code, big deal.
| | 02:16 | But here's where it gets interesting.
| | 02:17 | There are two reasons why the
jQuery version is preferable.
| | 02:22 | First, with getElementById we need this
element to have an ID of myDiv in our
| | 02:29 | HTML, and if it doesn't have an ID in the
HTML, we can't get to it, but jQuery is
| | 02:36 | much more flexible that that.
| | 02:37 | We can give jQuery an ID to find by
using the hash or the pound sign, but we can
| | 02:43 | also find other parts of the page
that we can't get with getElementById.
| | 02:47 | For example, we can get all the
elements with a particular class just by using
| | 02:53 | the dot, the same way we would in CSS.
| | 02:56 | We can get all the elements of a
particular tag, like all the paragraphs or all
| | 03:01 | the anchors or all list items.
| | 03:04 | Now this piece in
parentheses is known as the selector.
| | 03:08 | We are telling jQuery what we want it
to find, and the selectors are really
| | 03:13 | borrowed from CSS, which is why we
use a pound or hash for an ID and a
| | 03:17 | period for a className.
| | 03:18 | And unlike getElementById, which
will only work on one individual piece,
| | 03:23 | anything we do with jQuery will
automatically work on all of the elements that
| | 03:27 | match the selector that
match what we are looking for.
| | 03:30 | Now we can even refine it more than this.
| | 03:34 | We could combine a couple of these.
| | 03:35 | For example, in this case, p.description,
give me all the paragraphs that have a
| | 03:41 | class of description already on them.
And there are also certain words we can
| | 03:46 | add to further refine this like
:first, :last, :contains, :visible.
| | 03:54 | The way these would be used, again,
is combining them with other parts of the selector.
| | 03:59 | So let's take a look at how.
| | 04:01 | So I have switched over to a file of
some JavaScript, which I have mostly
| | 04:05 | commented out here, so I can go through this.
| | 04:07 | Right now, we are using the standard
DOM way of getElementById, which is going
| | 04:13 | to apply a CSS highlight to this
main section here, main article.
| | 04:18 | It looks kind of ugly, but it's
proving the point that this actually works.
| | 04:21 | Comment that one out.
| | 04:23 | The JQuery version here would just be
finding the div and adding the class of highlight.
| | 04:28 | We are going to get more into why this
is better in just a minute anyway. But we
| | 04:32 | can get more flexible than that.
| | 04:35 | I can simply say JQuery.tourdescription to
find all elements with a particular class.
| | 04:41 | Jump back over to the web page and
refresh it, and I can actually see that that
| | 04:46 | class is being applied to
several different elements on the page.
| | 04:53 | Similarly, I could apply that class
to all the elements that were list
| | 04:57 | items just by doing this.
| | 04:58 | This doesn't use the pound sign or the dot;
| | 05:01 | it just says li or p or a for a list
item or a paragraph or an anchor tag.
| | 05:08 | Refresh that page, and we can see that
both here where I got list items and
| | 05:13 | down at the bottom
| | 05:14 | it's looking rather ugly, but it proves
the point here that it is actually being
| | 05:17 | applied to multiple elements at the same time.
| | 05:21 | We can take that a little further, commenting
that one out and then adding the :last to it
| | 05:27 | we will first find all the list items
in the entire DOM and then we'll add the
| | 05:33 | class to the very last one.
| | 05:35 | If I refresh this, now we can
see that that works as well.
| | 05:41 | And I can go even better than that.
Using the :contains word in jQuery,
| | 05:47 | we can tell that our selector will
find all paragraphs and then filter them
| | 05:51 | down to say only the ones that contain the
word 'packages' and then add the class of highlight.
| | 05:57 | So saving that, refreshing the page
and scanning back up, I can see that
| | 06:02 | it's applying that class to
several of them, as long as the paragraph
| | 06:06 | contains the word packages.
| | 06:08 | So with jQuery, there are many ways to
get immediately to very specific parts of
| | 06:13 | the page without needing an ID on them.
| | 06:17 | So with the selector, we are
telling jQuery what to look for.
| | 06:20 | Then we have a dot, and then we tell
it what we want to do, some action, some
| | 06:25 | change that we are doing.
| | 06:26 | In this case, jQuery find the ID of
myDiv and then add the class of highlight.
| | 06:33 | Now the second reason why this is
better is that addClass is much more flexible
| | 06:39 | than just using className
with our document.getElementById.
| | 06:44 | See, when we use className it's a
property. We're just setting it; it will
| | 06:48 | overwrite any classes that were there before.
| | 06:51 | But when we use addClass with jQuery
it adds our new CSS class and keeps
| | 06:57 | any that were there before, so we can start
stacking our CSS classes up on our elements.
| | 07:02 | And not only do we have an addClass,
| | 07:04 | we also have a removeClass method in
jQuery and a toggleClass method in jQuery,
| | 07:09 | which means if the class is not there, add it;
| | 07:13 | if it is there, remove it. And this
is a great little microcosm of what
| | 07:16 | jQuery is all about.
| | 07:19 | It's more accurate. It's more flexible.
| | 07:21 | There are more choices.
| | 07:22 | It's kind of what you wish
JavaScript did in the first place.
| | 07:25 | Now we can make our code even shorter.
| | 07:28 | If you think that typing out jQuery
might get a little tedious because it's easy
| | 07:32 | to get the casing of this mixed up,
there's a shortcut so we don't have to.
| | 07:36 | We simply replace the word
jQuery with the dollar sign.
| | 07:41 | So the general format we are going to
use with JQuery is the dollar sign and
| | 07:45 | then in parentheses the selector, or
what to find, then a dot, and then some
| | 07:50 | action in any parameters we have to pass
about what to do, what do we want to do?
| | 07:54 | So what does the dollar sign mean?
| | 07:56 | Well, the dollar sign is just an
alias, a shortcut for jQuery itself.
| | 08:00 | Unlike languages like PHP, there is nothing
magical about the dollar sign in JavaScript;
| | 08:05 | it's just one of the accepted
characters in the variable name.
| | 08:08 | Dollar sign here is just a really
short variable name that points to jQuery.
| | 08:14 | So what else do we have?
| | 08:15 | Well, we have some great
ways of working with effects.
| | 08:19 | So I am going to just uncomment this
line of code here at Line 22, which is
| | 08:24 | going to use the dollar sign for jQuery,
tell it to find all paragraphs, and
| | 08:28 | then call hide with the parameter of 4000.
| | 08:33 | Saving that, I am going to jump over to
the browser and then just refresh this page.
| | 08:40 | Okay, I might not always want to do
that, but what hide is doing, as you can
| | 08:44 | probably tell, is taking 4000
milliseconds, or 4 seconds, to hide all paragraphs.
| | 08:51 | And the great thing is jQuery is
taking care of animating all this without us
| | 08:55 | worrying about set interval
calls or set timeout calls.
| | 08:59 | So we have got hide. We have got show.
| | 09:01 | We have got slide down, slide up, fade
in, fade out, all just as easy to use.
| | 09:07 | And then there are events.
| | 09:08 | Working with events in
jQuery is very simple indeed.
| | 09:12 | If I just uncomment these pieces of
code here, we can use the same selectors
| | 09:17 | the dollar sign, in this case an ID
of pageID.click, and in this case, passing
| | 09:22 | it an anonymous function.
| | 09:23 | Now what's this one going to do?
| | 09:25 | Well, it's easier to show.
| | 09:27 | Jumping back over and refreshing this page,
| | 09:30 | when I click on word TOURS, it
just changes to You clicked me!
| | 09:33 | We are using the #pageID to add the
click event and using that same selector
| | 09:41 | and using the text method here to set
its text value, rather than having to drill
| | 09:46 | down into the individual text node.
| | 09:49 | Again, very easy to add an event and very
easy to start manipulating that DOM element.
| | 09:55 | Not only that, but jQuery is also
very conscious of the word 'this.'
| | 09:59 | So if we use jQuery to add, for example,
a click event to all the h2 elements,
| | 10:08 | we can then be smart enough to know
which ever particular h2 is clicked will be
| | 10:13 | considered this every time that
this function is called, meaning what?
| | 10:19 | Jumping back over to the browser, as we
scanned down, I know that these are h2s
| | 10:23 | and when I click each individual one, it
knows exactly what caused that event to be raised,
| | 10:30 | so it's smart enough to
know which one gets changed.
| | 10:35 | And very simply, we could combine
both jQuery adding events and combine
| | 10:39 | jQuery's animation, so that very
easily, refreshing this page, every time we
| | 10:44 | click on the paragraph,
| | 10:46 | it's smart enough to
just disappear and fade out.
| | 11:00 | And one last thing here,
| | 11:01 | we are familiar with using
window.onload to call some script when we know that
| | 11:07 | the DOM is fully loaded.
| | 11:09 | One of the problems with window.onload
is if you accidentally write it multiple
| | 11:13 | times, only the last one will be
paid attention to, whereas in jQuery,
| | 11:18 | we have the $(document).ready function.
| | 11:22 | This does a very similar thing, meaning
that the code we put inside here will be
| | 11:27 | executed when the DOM is fully loaded,
but if we needed to, we could actually
| | 11:31 | call that same thing multiple times,
and we wouldn't have to worry about the last
| | 11:36 | one overriding the first one.
| | 11:38 | In this case, I am calling it twice.
| | 11:40 | Once I will change the content of this
page ID to "The DOM is fully loaded,"
| | 11:45 | and then in the next one, I am
going to set colors of h1 to red.
| | 11:48 | We refresh that page, and we can see
that both of those are being applied.
| | 11:53 | Now this is just a taste, a quick intro.
| | 11:56 | jQuery gets a lot deeper than this, of course.
| | 11:58 | So check out the documentation on
jquery.com or take a look at one of several
| | 12:03 | jQuery courses we have here at lynda.com.
| | Collapse this transcript |
| Using a content distribution network to deliver JavaScript files| 00:00 | We've seen that it's simple to
download jQuery so that you have a copy of the
| | 00:04 | file on your site to send to your users.
| | 00:07 | But there is a better way:
| | 00:08 | let somebody else do it.
| | 00:10 | Several companies, including Google
and Microsoft, allow you to link to jQuery,
| | 00:14 | and some other common libraries, and get
that file directly from their servers.
| | 00:20 | And they don't just have one server
but typically a bunch of geographically
| | 00:25 | distributed servers with
load balancing and failover, all in a Content
| | 00:29 | Distribution Network, or CDN, so it's
almost always faster for the user to get it
| | 00:34 | from one of their servers than from your server.
| | 00:38 | And using this is all free, and it's super easy.
| | 00:43 | All you do is in your HTML you find
your script tag where you're linking to the
| | 00:47 | local copy of the file and you just
change it to use, say, Google's link to it.
| | 00:52 | You're not changing
anything else about your own site.
| | 00:55 | You're still hosting your site and
your pages the same way you ever did, and
| | 01:00 | that's it; you're done.
| | 01:02 | If you ever wanted a reason to stop doing
this, you would just change this link back.
| | 01:06 | Now, more and more sites, even very
large ones, are using Google's CDN to deliver
| | 01:11 | JavaScript library files instead of
hosting it themselves, and there is really
| | 01:15 | a few benefits here.
| | 01:17 | First is the speed idea.
Google takes care on delivering that file.
| | 01:20 | They have a fantastic network and
they're very reliable, and any random user is
| | 01:25 | closer to a Google server than to your server.
| | 01:28 | So you don't have any bandwidth concerns.
| | 01:30 | Okay, jQuery and the like, they are small
files, but that bandwidth can still add up.
| | 01:35 | A three, a real benefit here is
when loading a page, browsers limit the
| | 01:41 | amount of simultaneous requests by
domain, so by spreading your assets across
| | 01:46 | domains, that can help, because one last
request to your server for JavaScript
| | 01:51 | means the browser can be making requests to
your server for other assets, like CSS and images.
| | 01:57 | And as more and more sites use
Google's CDN that file becomes effectively
| | 02:03 | shared across sites because of it
being cached in a user's web browser.
| | 02:08 | The idea is if your user visit, say,
site A, and they retrieve some HTML that's
| | 02:15 | linking to a JavaScript file stored on
a Content Delivery Network, they'll be
| | 02:20 | delivered that jQuery file, or whatever
it is, from that set path, and that path is
| | 02:26 | remembered and cached by the browser.
| | 02:29 | So if that user then goes to another
site and retrieves some HTML and CSS that's
| | 02:34 | also using that same CDN and that same
path, the browser will realize, hey, I've
| | 02:40 | already got a copy of that jQuery
file. I don't need to download it at all.
| | 02:45 | So I've talked about jQuery here,
as it's the most common, but if you want to
| | 02:48 | know what other libraries are
available, we'll get in more details, go to
| | 02:52 | code.google.com/apis/libraries.
| | 03:00 | Or if you don't remember that,
just search for Google CDN.
| | 03:03 | Now these are the current
ones that are available.
| | 03:06 | We've got Chrome Frame, Dojo, jQuery,
MooTools, Prototype, script.aculo.us, and
| | 03:12 | clicking any of them will give you a bit
more information about how you get hold of them.
| | 03:17 | Now when you browse through this
developer's guide you'll find a lot of content
| | 03:21 | about signing up for a Google API
key and using their loader JavaScript.
| | 03:26 | You really don't need to do this.
The most direct way is just to come on down to
| | 03:30 | the library that you're
looking for and find the path to it.
| | 03:33 | Now one more thing: you'll see that
Google makes this path available as https here.
| | 03:39 | That's where it showing up in this
list. In fact, it is available as both
| | 03:42 | http and https paths.
| | 03:46 | The main reason it needs to be
available as an https address is so you can use
| | 03:50 | it from an encrypted page without the
browser complaining that you're using an
| | 03:55 | unencrypted asset on that page.
| | 03:57 | There really is no other benefit to
encrypting jQuery; everybody knows what it is.
| | 04:03 | But if your site needs to link to
jQuery from pages at a variety of http and
| | 04:08 | https addresses, one shortcut is that
in your link to that file you actually
| | 04:14 | just remove the protocol from the
link, so you remove http: or https:
| | 04:20 | and just have the two forward slashes.
| | 04:22 | It looks a little strange, but that
will just use whatever protocol the
| | 04:26 | current page is using.
| | 04:27 | And that's all there is to it. The only
place I wouldn't use Google's CDN is if I
| | 04:33 | was developing a purely internal
intranet site where my users are literally in
| | 04:38 | the same building as the web server.
| | 04:41 | But otherwise, I highly recommend a
CDN as your default way of linking to a
| | 04:45 | library like jQuery.
| | 04:46 | There really are no downsides here.
| | Collapse this transcript |
|
|
12. JavaScript and HTML5JavaScript in HTML5| 00:01 | If you build web pages, you probably
know HTML5 is the newest version of HTML,
| | 00:06 | and it is the way the web world is moving.
| | 00:08 | It adds great new features to web
sites, many of which were previously only
| | 00:12 | available by using external plug-ins
like Flash or Java, but this will make them
| | 00:16 | part of the regular web, standardized
across all platforms across all devices.
| | 00:22 | And we're big fans of the HTML5 here at
lynda.com, but if you haven't done much
| | 00:26 | with it yet, it's often a
little confusing to approach,
| | 00:29 | particularly because HTML5 is talked
about along with other technologies, like
| | 00:34 | CSS3 and JavaScript.
| | 00:36 | And these aren't part of HTML5,
but they do typically come along for the ride.
| | 00:41 | And that is an important distinction.
| | 00:43 | HTML5 is not changing this arrangement.
| | 00:46 | It's HTML5 for your markup, CSS3 for your
presentation, and JavaScript for your behavior.
| | 00:52 | Now if you remember our discussion of
ECMAScript earlier in the course and that
| | 00:57 | what we're doing in this course is
ECMAScript 3, you might think, "Well, does
| | 01:01 | HTML5 mean I must have an ECMAScript 5?"
| | 01:04 | Unfortunately, it's not quite that
simple, and here is really the first
| | 01:08 | problem with the picture. HTML5 is not finished yet.
| | 01:12 | The specification is still a work in
progress, but that does not mean you should
| | 01:17 | be holding off thinking, "Well, I'll
wait and see if it gets implemented."
| | 01:21 | HTML5 is happening.
| | 01:23 | We know what's going to be in it.
| | 01:24 | There are pieces of it already
implemented in the latest browsers, and there are
| | 01:29 | things we can be doing
right now to work with it.
| | 01:32 | So what are these main features?
| | 01:35 | HTML5 brings new tags, new elements,
new abilities, and the main areas are
| | 01:40 | better support for video and audio
built into HTML itself, so we don't have to
| | 01:46 | use Flash plug-ins, for example.
| | 01:48 | There is a new element called Canvas that
will allow us to draw on the screen directly.
| | 01:55 | There is offline storage support, so
web sites can actually store a significant
| | 02:01 | amount of data, meaning they
can be used without a connection.
| | 02:04 | There are a whole lot of new form
elements for building better forms.
| | 02:09 | There is drag-and-drop support,
built-in abilities to drag and drop items, not
| | 02:14 | only within your own pages,
but actually between web sites.
| | 02:16 | There is Geolocation, understanding
of latitude and longitude built into
| | 02:22 | the language and local storage, being able
to store more data than just simple cookies.
| | 02:27 | And there are new JavaScript APIs.
| | 02:30 | What that means is it kind of makes
sense that there will be new objects and
| | 02:34 | methods in JavaScript, if we want to
write code that works with these features.
| | 02:39 | But here's an important thing.
| | 02:40 | These features are being implemented into
new browsers piece by piece, not as one thing.
| | 02:47 | Firefox 4 has core support for all the
main HTML5 features, but if you've had to
| | 02:52 | support Firefox 3, you'd lose most of them.
| | 02:54 | Similarly, Internet Explorer 9 has
support for just about everything, but if you
| | 03:00 | have to go back to Internet Explorer 8,
you're going to lose quite a lot of
| | 03:04 | this, and it's the same
story with the other browsers.
| | 03:07 | Now if you haven't come across this
site before, this is caniuse.com, and it
| | 03:12 | allows you to break down features of
HTML5 and CSS3 that are available in
| | 03:18 | the different browsers,
| | 03:20 | some of which have very good support,
but as you get further on you'll find
| | 03:24 | certain ones missing, and then the
general scorecard for how well the different
| | 03:29 | browsers are doing for each of those features.
| | 03:31 | But we're really focused on
JavaScript here, and while this course, as we've
| | 03:36 | mentioned, concentrates on the core of
ECMAScript 3, there are a couple of new
| | 03:40 | things that you should know about
that are coming along with HTML5.
| | 03:44 | In addition to the regular
getElementByID and getElementsByTagName that we know
| | 03:49 | about, we now have the much-requested
getElementsByClassName, which returns all
| | 03:55 | elements that match that class.
| | 03:56 | You can even tell it to find
multiple classes separated by spaces.
| | 04:01 | Most libraries like jQuery and
Prototype have implemented their own version
| | 04:05 | of this for years, but it's great to have it
finally natively supported in the language.
| | 04:10 | But this is really the only
general-purpose new method that I would associate
| | 04:15 | with HTML5, and it's not available
in Internet Explorer 8 and before,
| | 04:20 | so if need that functionality in
earlier browsers, look at using jQuery or
| | 04:25 | another Library, because most of the new
JavaScript abilities in the most recent
| | 04:30 | browsers are just support for those
new HTML5 features in those browsers.
| | 04:36 | Here's an example of that.
| | 04:37 | So in HTML5 there is a new video tag
in the markup, and while this does work
| | 04:42 | quite well on its own, if you grab
the video element object using, say,
| | 04:47 | getElementByID, you can then call
methods of it, like .play and .pause, and set
| | 04:54 | properties of it like the currentTime
and do that all through JavaScript.
| | 04:58 | And the object also has events, so we can
choose to listen out for say the ended event.
| | 05:04 | Now you might recognize that here I'm
using the addEventListener format for
| | 05:09 | working with events.
| | 05:10 | This is the one that I talked about
earlier in the course that I was avoiding
| | 05:14 | because of cross-browser differences.
| | 05:16 | But here, I can pretty much assume
that if I have a browser that supports the
| | 05:20 | video tag, it certainly
supports the addEventListener method.
| | 05:25 | And there are other events, such as
play and pause, that we can react to.
| | 05:29 | Now for more information about video,
take a look at our course, HTML5:
| | 05:33 | Video and Audio in Depth.
| | 05:35 | Similarly, HTML5 brings a lot of
storage options along with it that we can
| | 05:40 | target in JavaScript, from simple
localStorage where you just pick a name and
| | 05:46 | start storing and retrieving simple
values all the way to full offline support
| | 05:51 | allowing your site to be used as an
application without even requiring current
| | 05:55 | network connection. And then there is
Web SQL and something called IndexedDB,
| | 06:00 | really adding substantial
local storage abilities to the web.
| | 06:05 | And if you're interested in more
about this, check out our course on HTML5:
| | 06:09 | Local Storage and Offline Applications in Depth.
| | 06:13 | Now, HTML5 does have a new
JavaScript feature called Web Workers.
| | 06:17 | We'll be able to load JavaScript and
make it run in the background, regardless
| | 06:21 | of what else is going on in your page.
| | 06:23 | This is something that most other
languages can do, usually under the term
| | 06:26 | multithreading,
but JavaScript has never been able to do.
| | 06:30 | You can create a new Worker object and
point it to a separate file of JavaScript.
| | 06:35 | Now, the Worker object can't directly
affect the DOM, so you have to allow it to
| | 06:40 | generate events and send them back,
reacting to a message event from the Worker
| | 06:46 | the same way you might react
to a click event from the user.
| | 06:51 | And from your page you can send messages to
kick off certain functions in the Worker itself.
| | 06:57 | Now Web Workers aren't supported in
Internet Explorer yet, but are available in
| | 07:01 | Chrome, Safari, Firefox, and Opera.
| | 07:04 | And while there's obviously more to it,
you can tell that HTML5 is bringing
| | 07:08 | some interesting stuff
| | 07:09 | that's going to impact us
as JavaScript developers.
| | 07:12 | So the question is, what if
you want to use these features?
| | 07:15 | Well, you can't just ask,
does this particular browser support HTML5?
| | 07:21 | That's the wrong question, because as
you've seen, HTML5 is really not one thing.
| | 07:25 | It's a collection of features and
abilities all wrapped up and given this name HTML5.
| | 07:31 | And your responsibility as a
JavaScript developer is to be aware of the new
| | 07:35 | features that HTML5 brings, figure out
if they meet a need for you, and then
| | 07:39 | write any code to deal with that
particular feature, and perhaps to deal with
| | 07:44 | that feature not existing in an older browser.
| | 07:46 | So if you want to be an early adopter
with HTML5, you will be interested in
| | 07:51 | cross-browser differences.
| | 07:54 | Now, if you wrote any JavaScript more
than a few years ago, the idea of detecting
| | 07:58 | differences between browsers might seem
like a throwback to the bad old days of
| | 08:03 | trying to detect whether the
user was on Netscape or IE 4.
| | 08:07 | This is not the same thing
here that we're talking about.
| | 08:10 | We're not remotely interested in
browser detection, but we are interested
| | 08:16 | in feature detection--big difference.
| | 08:18 | You do not want to be worried about
writing code to detect whether the user has
| | 08:22 | Chrome version 12.1 on a Mac or
Firefox 3 on a PC, but we might want to ask,
| | 08:28 | does the current browser support
the new video functionality in HTML5?
| | 08:32 | If so, I'll use it;
if not, I'll do something else.
| | 08:35 | It's the specific features we care about.
| | 08:38 | Feature detection in JavaScript is quite simple.
| | 08:41 | You treat the feature as an object
and ask if it exists. Well, how?
| | 08:45 | Well, here I'm writing a
little bit of code to ask if the new
| | 08:49 | getElementsByClassName method
exists in the current browser.
| | 08:53 | And the way that I just do it is
just name it inside an if statement.
| | 08:57 | If it exists, this will be regarded as true.
| | 09:00 | Now very important, notice that here I'm
not calling the getElementsByClassName.
| | 09:04 | I'm not using the opening and closing
parentheses and passing any parameters;
| | 09:08 | I'm just using the name of
it inside our if condition.
| | 09:12 | And you can do this with any
of the future-facing objects.
| | 09:15 | First check if it exist, and if it
does, use it; if doesn't, ignore it or
| | 09:19 | fall back to some backwards-compatible way.
| | 09:21 | For example, if HTML5 video doesn't
exist, we can generate some elements to
| | 09:25 | include a Flash Player.
| | 09:27 | And next up, what I'm going to cover
is a very simple way to detect all the
| | 09:32 | HTML5 features that might or
might not be available in a browser.
| | Collapse this transcript |
| Using Modernizr| 00:00 | This is web development, so we'll be
working with browsers with different feature
| | 00:04 | sets for a long time to come.
| | 00:06 | And though we can rank most
ECMAScript 3 without caring much about
| | 00:09 | browser differences,
| | 00:10 | if you're going to be an early adopter
of HTML5 features, it really does become
| | 00:15 | an issue, and there's a great library you
should take a look at that will help you
| | 00:18 | build those HTML5-focused apps while
staying aware of backwards compatibility.
| | 00:23 | It's called Modernizr. It allows you to do easy
feature detection of both HTML5 and CSS3 features.
| | 00:31 | Kind of like working with JQuery or any
other library, you can simply download a
| | 00:35 | copy it from modernizr.com
and link to it on your web page.
| | 00:40 | Now it's suggested that you actually
put this file linked to in the head of
| | 00:45 | your document, as the code here needs to run
immediately, actually before the body tag loads.
| | 00:50 | It's very lightweight,
so that shouldn't be an issue.
| | 00:53 | Now as soon as it runs, what you'll
have is a new JavaScript object called
| | 00:58 | modernizr, with over 40 properties that
are just Boolean values to say whether
| | 01:04 | a particular HTML5 feature is supported.
| | 01:07 | So modernizr.video, modernizr.audio,
modernizr.canvas, modernizr.draganddrop.
| | 01:14 | Run it on one browser, you may get a
whole bunch of true results; and run it on a
| | 01:19 | different browser, you made a
couple of true and a lot of false ones.
| | 01:23 | What we can then do is just write code
that asks if modernizr.video, then yes
| | 01:29 | we have support for it.
| | 01:31 | We can generate some HTML5 video elements.
| | 01:34 | If that's false then perhaps we can
generate some flash video elements instead.
| | 01:39 | This will be the concept
of progressive enhancement.
| | 01:42 | If the user has that feature,
we will enhance the site with it;
| | 01:45 | if not, we might do nothing, or we
might fall back to an alternate method, but
| | 01:50 | what won't do is give
them something that's broken.
| | 01:55 | If you download the full version of
Modernizr from modernizr.com, it allows you
| | 02:00 | to check for every feature in HTML5 and
CSS3, and it would be very unusual for
| | 02:05 | me to actually need this.
| | 02:07 | So once I know exactly the features
that I'm looking for, I can go back and go
| | 02:11 | to their Production section where I
can just configure a custom build and
| | 02:16 | generate a smaller version with the
exact checks that I need. So, for example,
| | 02:20 | if I am only interested in drag-and-drop
and HTML5 audio support, I can then
| | 02:25 | tell it to generate that file, and I just
get the much smaller piece of code here
| | 02:31 | that I can use to say true or false
for just those particular features.
| | 02:35 | Modernizr does not, of course, give you
these abilities if they're missing;
| | 02:40 | it's simply a very straightforward
way to see if they're supported.
| | 02:44 | If you do want to get into more
advanced uses, it can help you load in what I
| | 02:48 | preferred to shims and polyfills,
which are ways of detecting a missing feature
| | 02:54 | and then trying to load in some
alternate code to emulate that feature, but that
| | 02:59 | is certainly beyond the scope of this course.
| | Collapse this transcript |
| Using Strict Mode| 00:00 | This next subject isn't strictly part
of HTML5, but it is a forward-looking
| | 00:05 | piece of JavaScript, so it
belongs in the same discussion.
| | 00:08 | You may come across references to
something called Strict mode in JavaScript,
| | 00:12 | particularly if you use
code checkers like JSLint.
| | 00:15 | Now, Strict mode is part of
ECMAScript 5, but even though we're focused on
| | 00:21 | ECMAScript 3 in this course, we might
well be interested in it for our own code.
| | 00:27 | It's a way to volunteer, to have your
JavaScript to be held to higher standards
| | 00:32 | than regular JavaScript, which has
we've seen, will let you be sloppy.
| | 00:36 | If you turn on Strict mode, for example, you
must declare variables before you use them.
| | 00:42 | If you fail to do so, that's an
actual error. Your script will break.
| | 00:46 | Strict mode will also cause an error
if you define a function with multiple
| | 00:50 | parameters with the same name.
| | 00:52 | There are several more things it will
complain about, a lot of them more advanced.
| | 00:57 | And to volunteer for
Strict mode you simply do this.
| | 01:00 | At the top of any file of JavaScript
you'd put the words "use strict" inside
| | 01:07 | double quotes, semicolon as its own line.
| | 01:11 | Adding it up here means I'm saying
turn on Strict mode for this entire file.
| | 01:16 | You'd also add it as the first line of
any function if you want to just do it
| | 01:20 | function by function.
| | 01:21 | But here's the thing,
only certain browsers support Strict mode.
| | 01:25 | Well, that's okay because browsers that
don't understand it will simply look at
| | 01:29 | this line, figure out it's a string
literal by itself, and just ignore it.
| | 01:33 | Browsers that do understand Strict
mode, for example Firefox 4, will then be
| | 01:38 | extra picky about your code.
| | 01:41 | So to prove that this works,
I'm actually first going to just remove this, so we
| | 01:45 | can run this code without Strict mode,
and it's a very simple piece of code here
| | 01:51 | that's just going to output the term
"Hello world" here to this area of my HTML.
| | 01:57 | And as I can see, Firebug
isn't giving me any errors here.
| | 02:01 | But if I jump back into the code and I
turn on use strict mode, save that again,
| | 02:08 | go back over into Firefox, and refresh this page,
| | 02:13 | instantly we have a problem.
| | 02:15 | It starts off here saying, "property
name samename appears more than once
| | 02:19 | in an object literal."
| | 02:20 | And bear in mind this is not just a
diagnostic message; the script has broken.
| | 02:25 | A moment ago it was actually changing
the contents of this div and now it is not.
| | 02:30 | So this line here where I am
creating a new object and I've given it two
| | 02:34 | properties with the same name,
that was forgivable in regular JavaScript.
| | 02:39 | It is not forgivable in Strict mode.
| | 02:44 | So I'll fix that one, go back refresh it again.
| | 02:48 | Now it's giving me another problem,
"duplicate formal argument A." It looks like
| | 02:51 | in this function I've declared three
parameters, but two of them have the same
| | 02:55 | name, and that's not going to do at all.
| | 02:56 | So I come back over here. Again, regular
JavaScript would let me get away with that.
| | 03:02 | It might have caused a logic problem,
but it would still have attempted to work.
| | 03:07 | Refresh it again, "assignment to
undeclared variable foo," foo = "Hello world."
| | 03:13 | That's because I'm not
using var at the top here.
| | 03:16 | So save that one, go back, test it again,
and then finally, we're working correctly.
| | 03:23 | Now I'm a fan of Strict mode, so I
actually tend to turn it on, but there are
| | 03:29 | two things to be careful of.
| | 03:31 | One, because it's common to combine
multiple JavaScript files into one when
| | 03:36 | you're trying to optimize performance,
make sure that if you're putting "use
| | 03:39 | strict" at the top of some of your files,
you're not then mixing them up with
| | 03:43 | some other files that don't use Strict.
| | 03:46 | And bear in mind you can use
Strict mode on a per-function basis.
| | 03:49 | And if you know you're going to be
combining multiple files together, some which
| | 03:53 | use Strict mode and some which don't,
| | 03:55 | you can combine the files with a
blank function wrapper, which might look a
| | 04:00 | little odd, but you do something like this,
| | 04:02 | where I'm opening a parentheses in a
function body at the top and I'm going to
| | 04:08 | close it using the following
format at the bottom, and then "use strict"
| | 04:15 | effectively is the first line
of this particular function.
| | 04:19 | This is actually what JSLint
currently recommends as a way of doing it, but I
| | 04:23 | think it's kind of clunky, but it's an option.
| | 04:26 | But secondly, and more importantly,
if you're going to be working with Strict mode,
| | 04:34 | don't turn it on and then only check
your code in browsers that don't support it,
| | 04:39 | because bear in mind even using
Strict mode, or turning it on, your code may
| | 04:43 | still work in non-strict browsers and
only break in Strict mode in a supported
| | 04:49 | browser, so make sure you check it
across multiple different browsers with the
| | 04:54 | different capabilities.
| | Collapse this transcript |
|
|
13. Advanced JavaScript FeaturesKnowing the JavaScript to avoid| 00:00 | JavaScript is not only the most
popular programming language in the world,
| | 00:04 | it's one of the most badly
written and because of its history,
| | 00:08 | there's a lot of bad JavaScript out
there on the web. And there are several
| | 00:12 | things you're likely to see when
reading JavaScript that I specifically chose
| | 00:16 | not to include in this course.
| | 00:18 | Now at this point, I'm going to tell you
a few of them, so you can recognize them
| | 00:22 | and make your own choice about
whether to look deeper at them or not.
| | 00:25 | And the first one is document.write.
| | 00:29 | This is very commonly seen
in early JavaScript tutorials.
| | 00:33 | It lets you write a string directly to
the current page, and as you can see from
| | 00:38 | this example, you can even
include HTML tags inside it.
| | 00:41 | Let me show you a basic example here.
| | 00:46 | So I've got a very straightforward
HTML page and instead of making a
| | 00:50 | separate JavaScript file, I've just got two
document.write calls inside a script tag here.
| | 00:59 | If I run this page, I'll see that this
is outputting some text directly into
| | 01:05 | the body of the page, whereas the previous text
is just here inside a h1 and the paragraph tag.
| | 01:13 | And it doesn't look so bad,
| | 01:16 | but there are a few issues with this.
| | 01:17 | See document.write doesn't work in XHTML,
| | 01:20 | it doesn't understand the DOM
properly, and it just spits out stuff
| | 01:24 | wherever it's placed.
| | 01:25 | It's a clunky inflexible way
of doing anything with a page.
| | 01:29 | And the most substantial reason that you
don't want to get used to it is because
| | 01:33 | you can only use it when
the page is initially loading.
| | 01:37 | If, for example, I decide to have a
function and put document right inside that
| | 01:44 | function and then I'm going to just
call that function a couple of seconds
| | 01:49 | after the page has loaded,
| | 01:51 | let's see what happens. So I save that.
| | 01:54 | I flip over to Firefox where we have it.
| | 01:58 | I refresh this page and two seconds
later, the document.write destroys the
| | 02:04 | original page, because it will only work as
the page is being created for the first time.
| | 02:09 | Run it anytime after the page is loaded,
| | 02:11 | it will erase the contents of the
document, so much better to use innerHTML,
| | 02:16 | or better still, to work with
creating and manipulating the individual DOM
| | 02:20 | elements and text nodes.
| | 02:23 | Next step is if you ever see
code that looks something like this,
| | 02:28 | browser-sniffing code. You're reading
something that seems to be detecting
| | 02:33 | Netscape or Microsoft Internet
Explorer or a particular platform.
| | 02:37 | This is really old-school stuff.
| | 02:39 | Browser sniffing, it used to be
necessary, but it hasn't been for several
| | 02:43 | years, and it's usually a dead giveaway
that what you're looking at is very old
| | 02:47 | code, or it's written by someone who hasn't
brushed up their JavaScript skills in way too long.
| | 02:52 | Any code that seems to be detecting
an actual browser or an actual platform
| | 02:57 | should be looked on with great
skepticism. While there might be a very
| | 03:01 | occasional edge case where you want to
do something with a particular browser,
| | 03:06 | in general, any detection we should do
is detecting features, not browsers, and
| | 03:12 | that's much simpler than working
with the navigator.userAgent properties.
| | 03:17 | Next step is the EVAL function.
| | 03:19 | EVAL is a powerful little function that can
take an expression and execute it as code.
| | 03:24 | That sounds a little weird,
so let me show you what I mean.
| | 03:27 | Let's say I create a variable a that's
a string and it contains kind of half a
| | 03:33 | statement here, and variable b contains
hello, and variable c contains a closing
| | 03:38 | single quote and closing parentheses.
| | 03:40 | What we can actually do is use EVAL
and then we could combine those three
| | 03:45 | variables together into one long string.
And if I pass it to EVAL function, EVAL
| | 03:51 | will actually cause that to
be executed as if it was code.
| | 03:54 | Now the issue is there are almost
always better ways to do it than EVAL.
| | 04:00 | This is really ugly.
| | 04:01 | It's hard to figure out what's
going on. It's inefficient.
| | 04:04 | It can lead to security problems,
because you're executing code that's stored in
| | 04:08 | variables and if you're reading one of
those variables from the outside world,
| | 04:11 | say the contents of a form field, it
can effectively inject code you didn't
| | 04:16 | write into your JavaScript.
| | 04:18 | It's generally agreed upon that EVAL is a bad
thing, so you might see it, but don't do it.
| | 04:26 | And the fourth thing I wanted to
mention is what's called a pseudo-protocol.
| | 04:29 | This is very common to see inside HTML.
| | 04:32 | It's a way of making a link or a
button directly call a function.
| | 04:37 | So in a regular HTML anchor tag,
instead of having an a href equal to the address
| | 04:43 | of a web page using HTTP, we have javascript:
| | 04:47 | and then say the name of a function.
| | 04:50 | This is called a pseudo-protocol,
because usually what you'd be doing here
| | 04:54 | is linking to http: or https:
| | 04:56 | and those are real Internet
protocols; javascript: is not.
| | 05:02 | It's just a way of telling the
browser to call a JavaScript function here
| | 05:06 | instead of going to an actual address.
| | 05:07 | Okay, it looks pretty easy,
but what's the problem?
| | 05:10 | Well, one, you're mixing your HTML
with your script, not a good a thing in
| | 05:14 | principle; and two, if
JavaScript is disabled, this is useless.
| | 05:19 | You have a link that does nothing.
| | 05:20 | Now there is a similar format that's
slightly better, where you use the name of the event.
| | 05:27 | So in this case I do actually have an
href here that's pointing to an actual
| | 05:31 | page, an actual address, and then I have
onclick=, in this case someFunction; return false.
| | 05:38 | This is preferable to the pseudo-protocol.
| | 05:41 | Here, at least I have treated this link
as the link it's meant to be, with a real
| | 05:45 | address, and I've added the
onclick handler as a separate attribute.
| | 05:50 | Now what you often see here is the
statement "return false" and this is here to
| | 05:54 | stop the default behavior of this link,
which would be to follow the actual link here.
| | 06:00 | So in this case, if JavaScript is
enabled, we will run the JavaScript
| | 06:04 | function called someFunction and if
not, we would call the JavaScript HTML
| | 06:10 | link and follow that link.
| | 06:11 | And I'm not a big fan of this method
either, and I much prefer leaving my HTML as
| | 06:17 | pure content as possible and adding
event handlers directly inside my code,
| | 06:22 | which is why, all along in this course,
| | 06:24 | we've attempted to use JavaScript that
when it runs adds functionality to an
| | 06:29 | existing page that already works,
since, again, this is the concept of
| | 06:33 | progressive enhancement.
| | Collapse this transcript |
| Introduction to regular expressions| 00:00 | JavaScript, like many programming
languages, if not all of them these days, has
| | 00:05 | regular expressions built into the language.
| | 00:07 | Now, regular expressions are
odd-looking sequences of characters that describe
| | 00:12 | and can match patterns and strings.
| | 00:15 | They let you verify that a credit card
number has the right amount of digits,
| | 00:18 | or that an email address, or URL
matches a basic pattern, or that a password
| | 00:24 | has a mixture of uppercase and lowercase
letters, or just define certain words in a larger string.
| | 00:30 | Now nobody finds regular expressions
pleasant to begin with, but they are very
| | 00:33 | useful, and there is always two parts to them:
| | 00:36 | first you create the regular expression
that describes the pattern that you are
| | 00:40 | looking for, and then you apply it to
something else to see if it matches.
| | 00:44 | So step one, we describe the regular expression.
| | 00:47 | We can create a variable in JavaScript.
| | 00:50 | I've created one called myRE for my
regular expression and set it equal to /hello/.
| | 00:57 | This is almost like creating a string
variable except we don't use quotes but
| | 01:02 | forward slashes to mark
the beginning and the end.
| | 01:05 | Now, this is actually a shortcut in
JavaScript for the longer version, which
| | 01:09 | we could use the new keyword, new RegExp, or
regular expression object and pass in hello.
| | 01:16 | These both would create the same variable.
| | 01:19 | It's the same way that we can
create a new array object or use square
| | 01:22 | brackets as a shortcut,
| | 01:24 | we can make a new regular expression
object or use the forward slashes as a shortcut.
| | 01:28 | Now this is about as
simple a pattern as you can get.
| | 01:32 | It's just going to look for the word
hello to exist somewhere in a string to
| | 01:36 | be matched against.
| | 01:38 | So I can then create a new string, in
this case call it myString, and what I am
| | 01:43 | going to do is call the test method of
my regular expression against my string.
| | 01:50 | So if myRE.test, pass myString in,
does that word hello occur? Yes, it does.
| | 01:55 | We'll pop up an alert.
| | 01:56 | Now this is case sensitive.
| | 01:59 | Calling test will just return true or false.
| | 02:02 | If you called search instead, you would
actually return the position of the first match.
| | 02:07 | Now, a complex pattern than just
single words are created by using special
| | 02:14 | characters, so as an example if I
created a regular expression variable with
| | 02:20 | the carrot symbol, this would denote
the start of the word or the string that
| | 02:25 | we are matching it again.
| | 02:26 | So hello would have to appear
right at the start of the string.
| | 02:31 | On the flip side, hello with a dollar
sign at the end means hello would have to
| | 02:34 | appear at the end of the string.
| | 02:36 | And we can get even more specific.
| | 02:40 | If I use a plus sign somewhere in the regular
expression, that means the previous
| | 02:45 | character, in this case L, has to
appear once or more, which in this case would
| | 02:50 | match for hello with one L, hello with
two Ls or hello with a dozen or 500 Ls.
| | 02:57 | If I instead used an asterisk, that
would be zero or more times, so the previous
| | 03:02 | character L would have to be there zero
or more, which means it would also match
| | 03:06 | on h-e-o, so no L at all. And then we
can also use a question mark, which means
| | 03:12 | just zero or one, so h-e-o would match,
h-e-l-o would match, but any more Ls than
| | 03:18 | that would not match.
| | 03:22 | If I use the pipe, it means either/or.
| | 03:25 | In this case, it'd be true if the
string contained either hello or goodbye.
| | 03:32 | If I use the point here, it means any
character, which would much a whole bunch
| | 03:36 | of different things.
| | 03:37 | Now you will also see the backslash
used a lot with regular expressions.
| | 03:43 | So \w used as one little piece here
means that this must be an alphanumeric
| | 03:49 | character or an underscore.
| | 03:50 | \b means a word boundary, like a space
or a new line, which means here that hello
| | 03:58 | would have to appear after a space or
after a new line as a word by itself and
| | 04:03 | not as part of another word.
| | 04:05 | And very often you'll also see the
square brackets being used to denote a range
| | 04:10 | of characters to match on.
| | 04:12 | So in this case, I've got c-r-n-l-d
inside square brackets. That means any of
| | 04:17 | those letters followed by o-p-e will
be regarded as true, but if I have a
| | 04:23 | different letter, it will not.
| | 04:25 | Now as you're probably beginning to tell,
there's a lot of these things, and there
| | 04:31 | is way more than I can show you here.
| | 04:33 | What we start to do is describe more complex
patterns by starting to string them together.
| | 04:40 | So as an example, here is one that
would check for a valid format for a US ZIP
| | 04:45 | code with an optional four-digit extension.
| | 04:49 | We are surrounding it with the forward
slashes at the start and end. Then we are
| | 04:53 | using the carrot at the start to denote
the start of the string and saying what
| | 04:57 | characters allowed, how many characters
there can be, and then the question marks
| | 05:01 | to denote whether things are optional or not.
| | 05:03 | Now, bear in mind you're likely to
begin by finding examples of these online.
| | 05:09 | If you're looking for a regular
expression to match a credit card number format
| | 05:13 | or a date or a password, there is
really no reason you should be writing it
| | 05:16 | yourself from scratch.
| | 05:17 | Now, oftentimes the best
regular expression is a matter of some
| | 05:20 | considerable debate.
| | 05:22 | People have been arguing for many
years on what the so-called ideal regular
| | 05:27 | expression for an email address would be.
| | 05:29 | Now, here is actually very simple one.
| | 05:31 | What this is saying is that the first
part of the line begins with a carrot and
| | 05:35 | then after than we can have multiple
letters, digits, periods, dashes and
| | 05:40 | underscores. Then the @ must exist
and then more of these matches where we
| | 05:46 | can't use the special characters, then
at least one, and then it must end with
| | 05:52 | the top-level domain, which can be
two to four letters like.com.net.org or a
| | 05:58 | country code like UK.
| | 06:00 | But here's the thing, email regular
expressions are notoriously difficult, and
| | 06:05 | this one actually isn't correct.
| | 06:06 | It won't allow long top-level domains
like.museum, which might be rare, but
| | 06:11 | certainly does exist.
| | 06:12 | And it doesn't allow plus signs in the
email, which can be used by some mail systems.
| | 06:17 | In fact, the range of permissible email
addresses is more complex than you might
| | 06:21 | think, and if you include non-Western
character sets, you should get into more
| | 06:26 | complex regular expressions that are
dozens, or even hundreds, of lines long.
| | 06:30 | There really is no perfect
regular expression for validating email.
| | 06:33 | There is just a variety of ones that
are good enough, and this is worth bearing
| | 06:38 | in mind with regular expressions.
| | 06:40 | There is a lot of knowledge out there.
| | 06:42 | Right now, what you need to
understand is what they are and how they used.
| | 06:46 | Regular expression syntax is not
something you need to memorize just yet, if
| | 06:50 | you've never come across them before.
| | 06:52 | They are a tool, and there are
something to be used when you need them.
| | Collapse this transcript |
| Working with AJAX| 00:00 | One of the reasons for the resurgence
of JavaScript in recent years is the
| | 00:04 | enormous popularity of
what's come to be known as AJAX.
| | 00:07 | Now, AJAX sounds like a separate
technology or a language; it isn't.
| | 00:12 | It's just a useful buzzword to describe a
cool technique we can do with JavaScript.
| | 00:17 | While it officially stands for
Asynchronous JavaScript and XML, well, it's
| | 00:22 | really more to do with AJAX being a
good acronym than anything else, because it
| | 00:26 | doesn't even require XML.
| | 00:28 | As far as we're concerned, AJAX is JavaScript.
| | 00:32 | It's just a very specific use of it.
| | 00:34 | What it means is that after a web
page has opened in the user's browser, we
| | 00:41 | can have JavaScript behind the scenes
communicate back to the server, even
| | 00:46 | pass and retrieve data, and update
parts of the page without the entire page
| | 00:51 | itself needing to reload.
| | 00:56 | A simple example, if you've used, for
example, Google, and started typing, and
| | 01:02 | found it able to start to fill out the
information that it thinks you're looking
| | 01:06 | for and actually update the page as
you're typing, this is AJAX going on.
| | 01:13 | As I'm typing, JavaScript is passing
these characters to the web server, which
| | 01:17 | is then returning the most likely
results as I type and updating the page
| | 01:21 | without me actually refreshing the page at all.
| | 01:24 | If you use an online map, the ability
to scroll into places, or to zoom in and
| | 01:29 | as I zoom in start seeing more and more
explicit data is the same idea, that this
| | 01:34 | is being fetched from the
server as I'm using the Zoom button.
| | 01:38 | Now, in a lot of cases this is almost
transparent if I'm working with it slowly,
| | 01:43 | but if I start to drag quite quickly,
you'll often see it hurrying up to try and
| | 01:47 | fill in that data for me.
| | 01:53 | Either way, it's certainly usable.
| | 01:54 | So this technique, this AJAX ability,
lets you make more responsive sites,
| | 01:59 | sites that can behave like real
applications. And for things like search,
| | 02:03 | autocomplete, and maps, being able to load data
on the fly actually makes these sites possible.
| | 02:08 | There is no way we could
load all the data upfront.
| | 02:12 | AJAX builds on all these skills we've
been working with so far: understanding
| | 02:15 | basic JavaScript, grabbing
and manipulating DOM elements.
| | 02:19 | There are two new things
we need to be able to do.
| | 02:21 | One is, from JavaScript, create an
object that will call the server.
| | 02:26 | We're creating a request here.
| | 02:29 | And two, then is a very separate part,
is let the server pass information to us
| | 02:35 | to deal with any response.
| | 02:37 | Now, these are done as two distinct
steps rather than say one function call,
| | 02:41 | because we don't know how long it's
going to be between the request and getting
| | 02:45 | the response, and we don't want
to hang the page while we wait.
| | 02:48 | This is the asynchronous part of AJAX.
| | 02:51 | So how do we do this?
| | 02:52 | Well, to do it we work with a new
object, the XMLHttpRequest object.
| | 02:58 | This is the middleman between our
page loaded in the browser and the server
| | 03:03 | side, any communication we want to do.
| | 03:05 | But unfortunately, it's actually one
of those objects with a cross-browser
| | 03:09 | difference, so I can't just write a
line of code like this that creates it.
| | 03:13 | I first have to see if it exists.
| | 03:17 | So what I do is something more like this.
| | 03:19 | I'll just define the variable,
and then I'm going to do a feature check,
| | 03:23 | ask if certain objects exist on this browser.
| | 03:26 | In this case, what I'm asking is if
(window.XMLHttpRequest). That doesn't do
| | 03:32 | anything except ask,
is there an object of this name?
| | 03:35 | If there is, I know I'm on Firefox or
Safari, or a browser like that, and I can
| | 03:39 | then go ahead and create a new XMLHttpRequest.
| | 03:44 | If that returns false, I'll then
go on and check, well, do you have
| | 03:48 | window.ActiveXObject?
| | 03:49 | If that's true then I'm running on
Internet Explorer, and I will create it as
| | 03:54 | the Microsoft.XMLHTTP object done this way.
| | 03:58 | This is one of those areas where you
can't really blame Microsoft for being a
| | 04:02 | little different, because they
actually did invent this object in the first
| | 04:06 | place. So they're not just trying
to do a different version of it;
| | 04:08 | they just have their own
specific reasons for creating it.
| | 04:11 | Now, what I have to do after this is
I haven't yet said, what am I calling?
| | 04:16 | Where on the server am I reaching to?
| | 04:18 | Have I executed this request or not?
| | 04:20 | So I do need to go ahead and configure
and send it, but not yet, because I first
| | 04:26 | have to tell it what to do
when a response comes in.
| | 04:29 | That's the second part of this.
| | 04:31 | Now, that request object, when we
execute it, will start to kick off events the
| | 04:37 | same way as a lot of things kick off events.
| | 04:39 | The one we're really interested in
will be the onreadystatechange event.
| | 04:45 | And the same way as dealing with say a
userClick event or a windowLoad event,
| | 04:50 | we say, okay, when this event is
occurring on that request object, I'm going to
| | 04:54 | call, in this case, an anonymous function,
which right now will just output a message to console.log.
| | 05:00 | However, as we'll see, this event is
actually quite chatty, and the request will
| | 05:04 | cause this event to be called multiple
times before we're completely finished
| | 05:08 | with the entire communication request.
| | 05:11 | I'll get into that in just a moment.
| | 05:13 | But after I've been prepared to accept
this response, after I've created this
| | 05:17 | event handler, then I can configure and send it.
| | 05:20 | I tell it where the request is going.
| | 05:22 | In this case, I say I am
using a GET rather than a POST.
| | 05:26 | I am going to call the address, in
this case, mysite.com/somedata.php.
| | 05:33 | The last argument here of true means yes,
this is asynchronous, so as soon as we
| | 05:37 | do it, we're going to go ahead and
execute any other JavaScript code, and we're
| | 05:42 | just going to allow the browser
itself to handle any response--
| | 05:45 | we're not going to wait
for it. And then we send it.
| | 05:49 | I am passing Null here, but if I had some
parameters to send, I could do that too.
| | 05:54 | So let's see a simple example in code.
| | 05:58 | I have about as straightforward
an HTML page as I can have here.
| | 06:02 | I've got one div called mainContent
with "This is an AJAX Example," and in my
| | 06:08 | script file that I'm linking to, I
have some simple boilerplate code for
| | 06:12 | creating this AJAX request.
| | 06:15 | So on Line 4, I defined a variable
called myRequest. On Line 7 I am going to
| | 06:21 | ask, if the XMLHttpRequest object exists.
| | 06:25 | If so, we're in Firefox or
Safari, I'll go ahead and create it.
| | 06:28 | If not, we're probably in IE, so I'll
go ahead and create it the different way.
| | 06:32 | Either way, by the time I get to
Line 14, I should have an object.
| | 06:35 | I am going to create an event handler
for our request, which in this case we'll
| | 06:39 | just call console.log, and say, "We were called!"
| | 06:43 | Line 19, now I have to configure
that request. Where is it going?
| | 06:47 | In this case I am going to say to a GET,
and I've just given it the address of
| | 06:51 | simple.txt, which is effectively
going to treat it as a relative link here.
| | 06:55 | I wanted to do it simply so that I
didn't have to work with creating up server-
| | 06:59 | side scripts, all that kind of thing.
| | 07:01 | I do have a file that's existing at
the same location as my HTML page and
| | 07:06 | my JavaScript file.
| | 07:07 | It's just called simple.txt and it says,
"This is the contents of a simple text file."
| | 07:13 | So that's what we're after.
| | 07:15 | And then we're going to send the request.
| | 07:17 | Now, after I execute this code if I did
have more JavaScript code, it would just
| | 07:22 | go on and execute any subsequent JavaScript.
| | 07:26 | We're not waiting for the request to come back.
| | 07:29 | That's why we set up the event handler.
Because whether that request takes 10
| | 07:34 | milliseconds or 10 seconds,
we don't want to block,
| | 07:38 | meaning we don't want to hang the page.
So we just go ahead, and when it calls
| | 07:42 | this back, it will jump back
here into this anonymous function.
| | 07:46 | So let's see if this works.
| | 07:47 | I'm going to jump over and just
execute this code, open it up in Firefox.
| | 07:55 | Now, I do have my console open here,
and I can actually say that I got that
| | 08:00 | console.log message that we were called
five times, which is a little strange.
| | 08:05 | Well no, it's not, really.
| | 08:07 | The thing is is that this
onreadystatechange event actually gets called multiple
| | 08:12 | times, and every time it's called it's
at a different stage of the request and
| | 08:17 | response, and it passes in a
little piece of information.
| | 08:21 | I am going to write that out,
so you see what it looks like.
| | 08:23 | I am going to say console.log.
I have a property of the request
| | 08:33 | object called readyState.
| | 08:35 | So if I save this, go back over and
refresh it again, I can see that I get
| | 08:39 | called several times with a
different state: 1, 2, 3, and 4;
| | 08:43 | in fact, 4 is the one that I am interested in.
| | 08:45 | When there is a ready state of 4, I
then know that I've gotten a response back
| | 08:50 | from the server from whatever I was asking for.
| | 08:56 | So what I am going to do is just
put in a little bit of code here.
| | 08:58 | I am going to be starting
off with an if statement.
| | 09:01 | If (myRequest.readyState === 4) meaning
I know I've got a response back, then I
| | 09:07 | am just going to call a few DOM methods here.
| | 09:10 | First, I am going to create a new
paragraph element and call it p. Then I am
| | 09:15 | going to create a new TextNode.
| | 09:16 | Now, here's the only important bit about this.
| | 09:19 | We've seen everything except this.
| | 09:22 | Once that response has been received,
I will have a property of the request
| | 09:26 | object called responseText, and that's
going to be whatever I got back from that call.
| | 09:32 | So we create the element.
| | 09:33 | We create a TextNode with that content in it.
| | 09:36 | I then add the TextNode to the paragraph.
| | 09:38 | I then add the paragraph to the
DOM tree, to the mainContent div.
| | 09:44 | So save this file, jump back over into
the browser, and what I am hoping for is
| | 09:49 | when I refresh this I will see the page
itself updating that content. There we go!
| | 09:53 | This is the contents of a simple text file.
| | 09:57 | Now, obviously because all my files are
running locally, what I am not seeing is
| | 10:01 | perhaps the slight delay that I might
have in updating this page, but this is
| | 10:06 | still proving the point.
| | 10:07 | Yes, it's a simple example here,
but the entire process of doing this in a
| | 10:11 | production site is the same.
| | 10:13 | We're creating a request, we're setting
up a handler to wait for any response,
| | 10:18 | and then we're firing the request off.
| | 10:21 | Now, as with other areas where there
are cross-browser differences, when I am
| | 10:25 | doing anything substantial with AJAX, I
am a fan of using a library like jQuery
| | 10:29 | which provides helper functions, so
you don't have to worry about writing the
| | 10:34 | cross-browser check, because it can
get a little more complex with older
| | 10:38 | browsers, for example.
| | 10:39 | So take a look at that if that's
an area that you're interested in.
| | Collapse this transcript |
| Working with objects and prototypes| 00:00 | In this course, we have
covered creating date objects.
| | 00:04 | We have covered creating array objects
and regular expressions, and these are all
| | 00:08 | built-in and predefined objects in JavaScript.
| | 00:11 | And we've even talked about how to make
our own simple objects, which we start
| | 00:15 | off by just creating new variables
that are wrapping several other variables
| | 00:20 | together under one name.
| | 00:21 | But we can go deeper with this idea,
and for those of you who are interested in
| | 00:25 | going deeper, particularly if you're
coming from another object-oriented language,
| | 00:30 | here's a quick introduction to the
concept of a prototype in JavaScript.
| | 00:35 | First, what can be a source of
confusion is that there is a popular JavaScript
| | 00:39 | library called Prototype,
but that's not what I am talking about here.
| | 00:43 | I'm talking about the prototype
built-in language future of JavaScript which
| | 00:47 | will help us create more formalized objects.
| | 00:51 | So what is the problem anyway?
| | 00:53 | Well, a quick recap.
| | 00:55 | We can create an object by using the
curly braces, or by using the words new
| | 01:01 | object, and in this case I'm using the
curly braces and I am loading it with
| | 01:05 | some initial values.
| | 01:07 | After this, I have this playerFred
variable that I can use, and I can add new
| | 01:12 | properties freely to him.
| | 01:14 | Properties are variables that belong
to this particular object, and I can even
| | 01:19 | add methods, which are functions that
belong to this object, and then call the
| | 01:26 | methods of that object. But there is
nothing that would stop me, for example, from
| | 01:30 | creating another object which looks like
it should have a similar structure, but
| | 01:34 | in this case would have high score
instead of score and have level instead of
| | 01:38 | rank. It just doesn't
match the general structure.
| | 01:41 | And this is what usually makes
programmers coming from other object-oriented
| | 01:45 | languages shudder because they want to
define multiple objects that share the
| | 01:49 | same description, and we can do this here.
| | 01:52 | We can formalize our own objects.
| | 01:55 | Now, for those of you coming from those
other languages, no, we don't get classes
| | 01:59 | in JavaScript, but we can kind of fake it.
| | 02:02 | So how do we do this? Well, step one,
| | 02:04 | we create what's called a
constructor function to make our new objects.
| | 02:09 | That really means we create a function
as normal with the name that we want to
| | 02:14 | use to create multiple objects from,
in this case Player, and by convention we
| | 02:19 | use an uppercase first
letter when defining this,
| | 02:22 | the same way that Date is an uppercase D
and Array is an uppercase A and Regular
| | 02:28 | expression has an uppercase R.
| | 02:30 | Then step two is we create a new
variable using the normal camelCase idea
| | 02:36 | and importantly, we use the word new
to create a new variable from that
| | 02:41 | Player constructor.
| | 02:43 | Now this will often seem a
little odd the first time you see it.
| | 02:46 | We have only seen the word new used
before with built-in JavaScript objects like
| | 02:51 | Date and Array and Regular expression,
but no, we can claim it ourselves.
| | 02:55 | This creates a new object and calls this
constructor function for this new object.
| | 03:01 | Now, there is nothing in this
constructor function right now, so we might want to
| | 03:05 | add a little data to the object.
| | 03:08 | Well, I could put the phrase this.name=fred.
| | 03:12 | If you remember, "this" is a word that we
can use to refer to whatever the current
| | 03:16 | object is, but I don't want to make all
my objects have a name of fred, so well,
| | 03:21 | here's where we use the
benefit that this is a function.
| | 03:25 | So what we can do instead is
make this constructor function
| | 03:28 | take a parameter, in this case we will
call it n, and then when we call it we
| | 03:33 | will actually create a new
player passing in the name Fred.
| | 03:36 | In this case, it will call the function
Player and set the current object's name to Fred.
| | 03:42 | So we now have an object
with that property inside it.
| | 03:46 | I could then call it again, creating
another new player object, but in this case
| | 03:51 | I'm creating a new object called Bob
with the Bob property set inside it.
| | 03:55 | So this is how I start to formalize my
objects a bit more than I could before.
| | 04:02 | So if I switch over to a very simple
piece of JavaScript where I'm doing
| | 04:06 | exactly that, I have a constructor
function here and I'm calling it once using
| | 04:11 | the new keyword to create this as an object.
| | 04:16 | In fact, if I want to give this object a bit
more in the way of properties, I am going to
| | 04:21 | do it internally here.
| | 04:22 | We are going to have a this.score = s
and a this.rank = r, and I will make this
| | 04:33 | function accept three parameters.
| | 04:36 | Now, hopefully this will make a kind of sense.
| | 04:38 | We are really just calling it like a
normal function, passing in three parameters.
| | 04:43 | But the most important piece is what I
am going to do next, which is that every
| | 04:50 | object in JavaScript has what's called
a prototype property, and functions like
| | 04:56 | the Player function I have just made
is an object in JavaScript, and I can use
| | 05:00 | that prototype property.
| | 05:01 | What I can do is call Player.prototype.
| | 05:08 | and then use this to attach to tie
new functions to this player object.
| | 05:14 | So I might decide that I want this
object to have a method called logInfo.
| | 05:20 | Now, this is completely up to me what I call it.
| | 05:22 | I'm going to set that equal to and give
it a function body here, and all I will
| | 05:28 | do with this one is make it write out
of console.log that writes out the message
| | 05:37 | "I am" then a comma and then this.name,
| | 05:41 | again, using this to say whatever the
name property of the current object is,
| | 05:49 | because we might call this
with 500 different objects.
| | 05:52 | I want to make sure it writes
out the right one for each one.
| | 05:56 | I could add another one in here.
| | 05:58 | Keeping the same general format,
I am going to say Player.prototype.
| | 06:02 | Well, let's give this one a promote method and
when promote is called it's going to say
| | 06:12 | this.rank++. Add 1 to whatever the rank
property of the current object is, and then we
| | 06:19 | will write out a message that
says, "My new rank is: this.rank."
| | 06:32 | And using prototype I am attaching
these functions to that constructor so it
| | 06:38 | means they'll automatically be
available on any object that was created
| | 06:43 | using that new keyword.
| | 06:44 | So down here after I create this new
variable called Fred, which is a new player,
| | 06:51 | I can say fred.logInfo, fred.promote.
| | 07:02 | Save that, jump over and open up
the page that's using this script.
| | 07:07 | If I have Firefox open--yup I do--
I can see in the Console here "I am:
| | 07:11 | Fred," "My new rank is: 6."
| | 07:14 | Now it seems like an awful lot of
trouble if I was just going to create one
| | 07:18 | thing, but of course the whole
benefit of this is I can now create a new
| | 07:23 | variable called Bob which is a new
player, and I will pass in three pieces of
| | 07:30 | information--the name, the score and
he rank--and I don't have to do anything
| | 07:35 | else to make this object
have the logInfo method.
| | 07:40 | It will automatically have it.
| | 07:42 | Same way it will have the promote method.
| | 07:45 | I can just start calling those.
| | 07:48 | Save that, jump over into the browser,
refresh that, and we are getting
| | 07:54 | information about the different object.
| | 07:57 | Create a third one, create a fourth one,
create a fifth, and so on. Each of them
| | 08:01 | will act independently of each other.
| | 08:03 | They will know about their own
properties and they will base everything that they can
| | 08:06 | do on both this constructor and any of
these methods that I've attached using
| | 08:12 | the .prototype property, without having to
separately attached them for each and every object.
| | 08:18 | Now, we are still in JavaScript, and it
is a super-flexible language, so I could
| | 08:22 | still dynamically start adding extra
methods and properties to each individual
| | 08:27 | object, but I don't need to here.
| | 08:30 | Now as you might expect, you can take
these idea of prototypes and of object
| | 08:34 | orientation in JavaScript much deeper
than this, but that's a subject for a
| | 08:38 | completely different class.
| | 08:40 | So for those of you looking for a
somewhat more formalized object-oriented
| | 08:44 | structure, this is certainly how you might begin.
| | Collapse this transcript |
|
|
14. Putting It All TogetherExample: Countdown| 00:00 | So let's put several of these ideas together.
| | 00:02 | I'm going to run through a few examples
to use the techniques and the concepts
| | 00:07 | we have already explored in
combination with each other.
| | 00:10 | And the first example I going to do here
is this Countdown page, where I can type
| | 00:16 | into the text box, put in, say, 3, and click
the button to say Start Countdown, and I
| | 00:21 | get this little JavaScript timer going on.
| | 00:23 | And this is not spectacularly impressive,
I grant you, but as you'll see, it's a
| | 00:28 | good example of several techniques put together.
| | 00:31 | Now step one, I have chosen to make
this page as simple as possible, so we can
| | 00:36 | focus on the script. And in fact, if I
look at the HTML here, I can see there
| | 00:40 | really isn't much going on.
| | 00:42 | I have got a little bit of basic CSS
at the top, but body of the page itself
| | 00:46 | is simply a container div which inside has
another div which has nothing in it and one h1.
| | 00:55 | And in fact on this page itself I don't
have the HTML for the text box or this button.
| | 01:00 | I'm going to generate that content
through JavaScript, and then I am going to
| | 01:05 | add the logic to work with it.
| | 01:07 | So let me open the JavaScript
and show you what's going on here.
| | 01:10 | First off, I have the
window.onload anonymous function here.
| | 01:15 | So as soon as the page is
loaded, I'm going to run this code.
| | 01:18 | And what we are doing here is
creating a couple on new elements.
| | 01:22 | I am using document.createElement here
to create a new input element. It's going
| | 01:27 | to be a text box, and I'm
going to give it an ID of minutes.
| | 01:31 | Then I'm going to create a button.
Again it's an input element, but this one
| | 01:35 | has a type of button.
| | 01:37 | I will give it some text, which is
"Start Countdown," and then I'm going to
| | 01:41 | associate the click event of that button
with a function called startCountdown,
| | 01:46 | which we will explore in a second.
| | 01:47 | And then finally these last two lines
simply take my two new elements and they
| | 01:52 | add them to the div called inputArea.
| | 01:57 | So that's what creates these parts of the page.
| | 02:00 | Now if I put in, say, some text here and
click this button, it's going to pop up
| | 02:04 | on alert called Please enter a number!
| | 02:07 | which makes sense. Let's see what's happening.
| | 02:11 | I said the click event is associated with the
function called startCountdown, and here it is.
| | 02:15 | The first thing we do is try and grab
the contents of that text box, which we
| | 02:20 | are using the.value property of,
and then I am using the isNaN function to check,
| | 02:26 | is it not the number?
| | 02:28 | So if this minutes variable is not a
number, I will pop up an alert, and then I
| | 02:32 | am just going to hit return, which
basically means I'm done with this function,
| | 02:36 | I'm not going any further,
| | 02:37 | I can't do anything else it
doesn't make sense anymore.
| | 02:40 | Now however, if it is a number, we will
just scoot right past that if statement
| | 02:44 | and then what I will do is I will find
out how many minutes they typed in, I will
| | 02:48 | multiply that by 60, and I will store it
in the variable called secondsRemaining.
| | 02:53 | Now, secondsRemaining is a variable
that's actually declared right at the
| | 02:57 | top of my JavaScript.
| | 02:59 | It is a global variable of which I have
two, just because I'm going to use those
| | 03:03 | from different functions.
| | 03:05 | So we create it there. What I'm then
going to do is called the setInterval
| | 03:10 | function. This is the one that
calls a method repeatedly. And the method we
| | 03:14 | are going to call is tick, and we are going to
call tick every 1000 ms, which is one second.
| | 03:19 | And if you remember from when we
originally talked about setInterval, if you ever
| | 03:23 | want to be able to clear the
interval, i.e., to stop this interval from
| | 03:27 | reoccurring, you need to grab a variable to it.
| | 03:31 | You need to grab a handle on it,
which you can then call later to
| | 03:34 | call clearInterval.
| | 03:35 | So we count the number of seconds.
| | 03:37 | We kick off the tick function every
one second, and then what I am going to do
| | 03:41 | is actually hide--it's not really a
form, but I am going to hide that input
| | 03:45 | area that has the text box and the
button, because I don't need to show it when
| | 03:49 | the clock is ticking.
| | 03:51 | So this must be more interesting
function, which is tick, which is defined
| | 03:54 | a little bit up here.
| | 03:55 | Let's bring this up and
just going through this one,
| | 03:58 | first line I will grab hold of a
variable called timeDisplay, and that is simply
| | 04:04 | grabbing hold all of h1, which is
showing the time. So it's just grabbing hold of
| | 04:10 | this part of the page.
| | 04:12 | Then what I'm going to do is turn the
seconds that I have, which is stored in the
| | 04:16 | seconds remaining variable,
into minutes and seconds.
| | 04:19 | The first thing I do is divide seconds
by 60. That will give me the amount of
| | 04:25 | minutes and then some
number after the decimal point.
| | 04:28 | So I use what's called the Math.floor
function, so that's a built-in part of
| | 04:33 | JavaScript, to say I want to take
something that might be 4.2 and make it just 4,
| | 04:39 | just make it a basic integer with
nothing after the decimal point.
| | 04:42 | Now I am using the term .floor rather than .round
because I don't want to round up and round down;
| | 04:48 | I just want to ignore any remainder.
| | 04:51 | I am just interested in the minutes.
| | 04:53 | Now in the same way, what I can do in
this next line is just figure out what the
| | 04:57 | seconds remaining are, and I am just going to
subtract minutes * 60 from seconds remaining.
| | 05:02 | That will give me the remainder.
| | 05:04 | Several ways of course I could calculate this.
| | 05:06 | On line 18 I am asking one
question: how many seconds are left?
| | 05:10 | And if those seconds are less than 10,
I want to add a leading 0 to it, because
| | 05:16 | if we are counting down, I don't want it
to say 1:1. Most digital watches and so on
| | 05:23 | will always have a leading zero
when your seconds get down beyond 10.
| | 05:27 | So this is what I'm doing here, and I
am using 0 as a string, so in the double
| | 05:32 | quotes, so that when these two are added
together, it will turn the number 5 into
| | 05:37 | 05 or the number 9 into 09.
| | 05:39 | I finally take both my min variable and
my seconds variable and add them together.
| | 05:44 | If you are bothered about official
type conversion, meaning that if min is a
| | 05:48 | number, how can I explicitly say it's a string,
| | 05:51 | I could use the dot to string method here.
| | 05:54 | I don't need to do that.
| | 05:55 | This would work just fine.
This concatenation will join the number that's stored
| | 05:59 | in min, then a colon, and then finally,
we change what the page actually displays.
| | 06:05 | The last couple of things to check is
did our seconds get down to 0, and if so, we
| | 06:09 | can pop-up an alert saying we are done.
| | 06:11 | We don't need to start
calling this tick function anymore.
| | 06:14 | So I will click clearInterval, and I
will finally call resetPage, which is going
| | 06:18 | to show the section of the page that
would allow me to kick the countdown off
| | 06:22 | again. And the very last line here is
subtract one from seconds remaining, because
| | 06:28 | this is a function that's called every second.
| | 06:30 | We want to make sure that we are counting down.
| | 06:33 | Finally, the resetPage function is this
one line here that's going to make the
| | 06:37 | input area display itself again.
| | 06:41 | And that's what's going to allow us to
do a little bit of error checking here and
| | 06:46 | then feed in a little bit of information.
| | 06:52 | And sure, this might be a simple
example, but we are using it to do all the
| | 06:59 | common JavaScript tasks.
| | 07:01 | We are creating DOM elements,
actually creating the page content
| | 07:06 | dynamically through JavaScript.
| | 07:08 | We are using events, both the
window.onload event and also the
| | 07:13 | button.onclick event.
| | 07:14 | We are doing error checking of the
input, making sure that in this case it is a
| | 07:19 | number before we try and do anything with it.
| | 07:21 | We are creating intervals to
repeatedly call functions every second.
| | 07:25 | We are hiding and showing parts of the page.
| | 07:28 | We are using the Math
object to do our calculations.
| | 07:32 | We are popping up alerts, and we are
grabbing and changing elements, and these are
| | 07:37 | all the same things that you will
be doing in every JavaScript program.
| | 07:40 | Now, this example certainly isn't
perfect. I could add more error checking to
| | 07:45 | check for a minimum and maximum value.
| | 07:47 | I could generate a pause button that
might show up when the countdown begins.
| | 07:52 | I could make the text change color as
it gets closer to zero, and you should be
| | 07:56 | able to figure out several ways
this could be improved and extended.
| | 07:59 | So take a look at it and see what you can do.
| | Collapse this transcript |
| Example: Resize| 00:00 | So let's deconstruct another example.
| | 00:03 | More than ever, these days we need to
realize that the amount of screen real
| | 00:07 | estate we have varies widely, from
30-inch-wide monitors to iPads, iPhones,
| | 00:12 | and other smartphones.
| | 00:14 | Now here's one JavaScript
approach for dealing with this.
| | 00:17 | Let's say I have a screen design for a
typical desktop, and it looks pretty good,
| | 00:21 | but if I resize and make it smaller,
to something like a smartphone, what it does
| | 00:26 | is change itself pretty
significantly with the layout.
| | 00:29 | Again, wider, we see a very visual display;
| | 00:32 | narrow, we see a text-focused display.
| | 00:35 | And the steps to do this are
actually very, very simple.
| | 00:38 | One, we need to write JavaScript that
realizes when the screen is being resized,
| | 00:44 | and two, we need to then detect the
actual size of the screen, because we need to
| | 00:48 | figure out is it getting made smaller or
is it getting made wider and change the
| | 00:53 | DOM in reaction to that.
| | 00:55 | Now I could start changing individual
attributes of DOM elements if I wanted
| | 01:00 | to and affect things with a fine scalpel,
but that's not really what I'm going to do.
| | 01:07 | Instead in this case, all I'm doing
is changing out the entire CSS file
| | 01:12 | that this page is using from
main.css, which is the default highly visual
| | 01:17 | file, to narrow.css.
| | 01:20 | And if I take a quick look at those,
main.css is my big CSS file with a lot of
| | 01:25 | stuff and narrow.css, well,
there is really not much to this.
| | 01:29 | In fact, this one is even doing some
basic tricks like hiding all the images.
| | 01:33 | So it's pretty sparse, but it proves the point.
| | 01:36 | My question is well, how do you change them?
| | 01:38 | And I change the CSS file
by reaching into my link tag.
| | 01:42 | Now up to this point, we've really
been working with more visual elements,
| | 01:47 | things like paragraphs and list items.
| | 01:49 | But there is no reason why I can't just
find, say, a link element. In this case,
| | 01:53 | it has an id of myCSS, and I swap
out the CSS file by just affecting the
| | 01:59 | attributes of my link element.
| | 02:01 | Now, this might be stored in the head
section of my document, but it's perfectly
| | 02:05 | accessible using JavaScript.
| | 02:07 | We have been used, so far, to affecting
things like paragraphs and list items, but
| | 02:12 | there is nothing to stop
us grabbing hold of this.
| | 02:14 | We give it an ID, in this case my CSS,
and I can change the attributes of this
| | 02:20 | just as easily as changing
attributes of any other element.
| | 02:23 | So if I jump over to the script.js
file, I can see what we are doing here.
| | 02:27 | There's an event on the
window object called onresize.
| | 02:31 | We have been working with onload so
far, which gets called once when the DOM
| | 02:35 | fully loads, but onresize gets called
multiple times when you start to resize
| | 02:40 | the browser window; in fact,
it gets called dozens of times.
| | 02:43 | It all depends on how fast
your machine actually is.
| | 02:46 | It might get called a lot.
| | 02:47 | So do be aware of that if the function that you
are calling actually does a lot of processing.
| | 02:52 | So every time it detects that the
window is being resized, it will call the
| | 02:56 | function called adjustStyle.
That's the whole breakdown here.
| | 03:00 | So the question is, what is adjustStyle?
| | 03:02 | Well, it looks like there's a lot of
code going on here, but in fact, we're back
| | 03:06 | mainly to cross-browser issues.
| | 03:09 | All I really want to do is get the
width in pixels, and I create a new
| | 03:13 | variable called width here.
| | 03:14 | But unfortunately, there's not a
super-reliable property that I can just access,
| | 03:19 | because it's different across browsers.
| | 03:22 | So what's happening here is we're doing
another little object detection here and
| | 03:25 | saying hey, do I have a
window.innerHeight object?
| | 03:28 | If I do, well, then I must
have a window.innerWidth object.
| | 03:31 | If I don't, then there is all sorts
of other combinations of do I have a
| | 03:35 | documentElement object,
and a clientHeight object?
| | 03:38 | If so, I can access clientWidth.
| | 03:40 | You should not bother about memorizing this,
because you're typically not going to use it.
| | 03:46 | You are going either copy it from
somewhere else or use a third-party library.
| | 03:50 | The end result is we should have a
variable called width. And in my case here,
| | 03:55 | what I'm saying is if width as
measured as being less than 600, I am going to
| | 03:58 | take grab the CSS element and
then set the attribute called href =
| | 04:03 | css/narrow.css, the path to the narrow file.
| | 04:09 | If it's not less than 600, we
will set it to the default one.
| | 04:12 | That's pretty much it.
| | 04:15 | Saving that, if we open up this
page, that's what detects, as we do the
| | 04:19 | resize, resize down,
| | 04:21 | it will change to the narrow.css. We resize up,
| | 04:24 | it will change to the wide one.
| | 04:26 | Now the only last thing
worth pointing out is this.
| | 04:29 | Let's say I resize down to a fairly
small size here and then I reload the page,
| | 04:34 | which as far as JavaScript is
concerned means we are loading from scratch.
| | 04:37 | Well, there is the problem;
| | 04:38 | we are loading the default.css file here.
| | 04:42 | That's because we are not actually resizing,
| | 04:44 | so this is never being called.
| | 04:47 | We are just opening the browser at a small size.
| | 04:50 | So one of the things I really want to do
here is just duplicate this function to
| | 04:56 | make sure that when we do an
onload the function is also called.
| | 05:00 | This will only happen one extra
time, so that shouldn't be a problem.
| | 05:05 | Now when I refresh this page, we
should load in at the correct size.
| | 05:10 | Again, this is a simple example
that takes us through multiple
| | 05:14 | real-world requirements.
| | 05:15 | We are dealing with events.
| | 05:16 | We are dealing with affecting the DOM,
even if we are grabbing and changing a
| | 05:20 | non-visible element like link.
| | 05:22 | And we are working with feature
detection and object detection to deal
| | 05:26 | with cross-browser issues, very much
day-to-day tasks for someone working with JavaScript.
| | 05:31 | And a third-party library like jQuery
would let me write simpler code here and
| | 05:36 | not actually worry about all this
code to deal with cross-browser issues.
| | 05:40 | And in a production site that's
typically what I'll use, because I have more than
| | 05:44 | one place that's going to need it.
| | Collapse this transcript |
| Example: Accordion| 00:00 | And let's do an example that uses
third-party libraries to add some pure visual
| | 00:05 | enhancements to a page.
| | 00:07 | So I have got this resources page here,
and it works fine, although this content
| | 00:11 | here can get a little long, a little heavy.
| | 00:15 | So what I'm going to do is use jQuery
and its associated language jQuery UI,
| | 00:20 | which you can get through this tab
here, or just from jqueryui.com, to add some
| | 00:26 | eye candy to this page.
| | 00:27 | Now while jQuery has some basic visual
effects, like fade in and fade out, jQuery
| | 00:34 | UI ads on and takes this even further.
| | 00:37 | It's simply another library that
uses jQuery to provide more user-
| | 00:41 | interface-focused behavior.
| | 00:43 | It has things like date pickers that we
can use, and it has Autocomplete buttons
| | 00:49 | that are really easy to start working with.
| | 00:51 | And there is also a collection of
effects. If you want to start animating certain
| | 00:57 | behaviors on your page you can do
things like pulsate certain divs or fade them
| | 01:02 | or fold them or even explode them.
| | 01:07 | What I'm going to do is use jQuery's
Accordion, and this is very simple to use,
| | 01:12 | the idea that we can have these
collapsing and expanding sections of content
| | 01:18 | where I click a header and get a
certain section of content beneath it.
| | 01:22 | And I'll be able to make this
happen with one statement of JavaScript.
| | 01:27 | So, how do I do this?
| | 01:29 | Well, into my HTML here, what I'm going
to do is down towards, the bottom I do
| | 01:34 | need to link to both jQuery and jQuery UI.
| | 01:37 | Now just to let you know, we've talked
about the idea of content distribution
| | 01:43 | networks. Both of them are available
from Google's CDN, so I could grab both
| | 01:48 | the path to jQuery and the path to
jQuery UI, or I could store them locally.
| | 01:53 | It doesn't really matter here.
| | 01:55 | What I'm going to do is just put them
in as script links here to the Google
| | 01:59 | CDN address and following them, I'm just
having a link to my own script file as well.
| | 02:05 | Now before I start writing any script,
of which I will need to do very little,
| | 02:09 | what I do need to do is just add a
few little markup pieces to my page.
| | 02:14 | I need to tell the Accordion
what areas it needs to control.
| | 02:18 | So if I come up a little bit, what I
have got here is this section. It actually has
| | 02:24 | the h3 as headers and the content for
the pieces that I'm interested in.
| | 02:28 | I have just split it out a little bit,
so we can see really a bit better where it
| | 02:32 | begins and where it ends.
| | 02:33 | What I am going to do first is surround
the entire section with a div. I am going
| | 02:39 | to give that div an id of accordion.
| | 02:42 | Now I don't have to here. Accordion
is not the magical name, but it will make
| | 02:47 | sense. I am just going to surround
the whole thing with that, opening div
| | 02:50 | and closing div tags.
| | 02:52 | Now inside that I need to mark out the
collapsing sections, and the pieces that
| | 02:56 | actually collapse are the paragraphs,
| | 02:59 | so I am just going to surround them all with
their own sets of opening and closing divs.
| | 03:04 | I don't need to give them any ID;
| | 03:07 | I just need to make sure that they have
an opening and closing div around them.
| | 03:15 | I'm just pasting in here when it's
opening and removing the forward slash.
| | 03:20 | So marking out each of those paragraphs,
and finally, in my HTML the user needs to
| | 03:26 | be able to click the
headlines for each of those pieces.
| | 03:30 | So what be accordion is going to expect
is that we just mark them with a
| | 03:34 | non-meaningful anchor tag, in this case a href=#.
| | 03:41 | And I'm just doing that inside the h3s
here, and this is all the prep that I need
| | 03:48 | to do on the page itself.
| | 03:52 | Just really marking it out a little bit.
| | 03:54 | Now I have no CSS for according, so this
is not going to make any visual change
| | 03:59 | to the page yet. In fact, just to prove
that, I will switch over to the browser and
| | 04:03 | refresh the page, and I can see the
page appears exactly as it did before.
| | 04:07 | I have just got a lot of paragraphs
of content, Customer notifications in
| | 04:12 | a big section, and Tour voucher in the
big section, Trip planning in a big section.
| | 04:16 | So the final stage I have linked to
the jQuery and jQuery UI, I've marked out
| | 04:22 | the page here, and I need
to do just one line of code.
| | 04:25 | Now, in my script.js file I do have a
wrapper here for window.onload, just so I
| | 04:30 | didn't have to type it, and because
I have jQuery, I don't need to use
| | 04:34 | document.getElementById. I can
just use the dollar sign. And what I am
| | 04:38 | looking for is the div which I called
accordion. Again, this can be any name but
| | 04:45 | accordion makes a lot of sense, and in
jQuery we use the pound or number or hash
| | 04:51 | sign to say yes, this is ID. Accordion.
| | 04:54 | Well, then what?
| | 04:55 | Well, by linking to jQuery UI, we will
have an accordion method. We are telling
| | 05:01 | it to go and accordion itself.
| | 05:04 | Save that file, and what'll happen is
this div look inside itself for its own
| | 05:09 | gives internally and collapse those,
all of them except the first one, and then
| | 05:14 | automatically add the code to allow
us to expand each of the section.
| | 05:17 | So I hit Save, I jump back over to the
browser, I reload this, and what I've got
| | 05:24 | is the first part looks just fine, but I can
see that the next section is already collapsed.
| | 05:29 | In fact, if I click on them, we
get a little accordion eye candy.
| | 05:36 | Now, the way accordions work, you only
ever have one section open at a time, and
| | 05:40 | it does that automatically, and it will
collapse the others and take care of animating them.
| | 05:45 | Now, I might add a little bit of
styling to make it more obvious that these
| | 05:49 | things can be clicked on, but it's
working just fine. Very easy to add this with
| | 05:54 | very little weight to the page.
| | 05:56 | Now one of great things about jQuery UI
is you don't have to load a copy of this
| | 06:01 | that has everything.
| | 06:03 | If I go back to the homepage of jQuery UI,
I can do what's called building a
| | 06:07 | custom download by clicking this
button, and then I can actually simply go
| | 06:11 | through and tell it now I don't
need the drag drop resize interactions.
| | 06:16 | I don't need most of the
widgets, but I do need Autocomplete.
| | 06:20 | I don't need any of the effects,
| | 06:21 | or perhaps I need Pulsate. And just
by selecting these, we can then download
| | 06:27 | our own little copy of it that's
just a zipped file with the very little
| | 06:31 | JavaScript that we need.
| | 06:33 | I don't need to do that right now
because I just decided to link to the whole
| | 06:37 | thing by using Google's CDN,
but it's nice to know that it's available.
| | 06:41 | And the great thing is because this
behavior is all being added using JavaScript,
| | 06:47 | there is no problem whatsoever if
JavaScript is disabled. This page would just
| | 06:51 | appear with all its parts expanded,
the way it was originally designed.
| | 06:55 | Now if, on the other hand, I'd written CSS
to hide these sections and then only used
| | 07:00 | JavaScript to open them up after the
fact, we would actually have real problems
| | 07:04 | if JavaScript was disabled. We would
have non-readable content for people.
| | 07:08 | And this once again is the idea of
progressive enhancement, adding behavior
| | 07:13 | to make your pages more interesting,
more compelling, while remaining
| | 07:17 | completely usable without it.
| | Collapse this transcript |
|
|
ConclusionWhere to go from here| 00:00 | In this Essential Training course we've
focused on the core knowledge to get you
| | 00:03 | up and running with JavaScript,
| | 00:05 | but of course, this language can go much
deeper than what we can possibly cover here.
| | 00:10 | But now what I'm really expecting is
that you have a problem you want to solve
| | 00:14 | with JavaScript, and no course is going to
tell you exactly what to do. So, now what?
| | 00:18 | Where do you go from here?
| | 00:20 | Well, we are web developers.
| | 00:21 | We make use of resources on the web.
| | 00:24 | We search for answers and tips and
tricks, but with JavaScript you really want
| | 00:29 | to be careful, because the problem is,
more than any other programming language I
| | 00:35 | know, the general level of advice
on JavaScript is abysmal on the web.
| | 00:40 | And some of the results you get, even
from very popular sites that might appear
| | 00:44 | highly ranked in search
results, is not to be trusted.
| | 00:48 | Now, most of the time that's not from
malice or even ignorance, but it's just old.
| | 00:52 | Some sites get highly ranked because
they've been around for many years.
| | 00:56 | That's the problem.
| | 00:57 | We don't write JavaScript
like we used to 10 years ago.
| | 01:00 | So I count myself in with other
trainers and authors who daydream that we could
| | 01:04 | just erase all the JavaScript advice
on the web and start again from scratch.
| | 01:08 | But that's not an option, so be skeptical.
| | 01:11 | If the answers that you find when
searching involve lots of document.write or
| | 01:15 | browser sniffing, that's a really bad
sign. Or if in general the code just
| | 01:19 | doesn't seem to know that the
DOM exists, look somewhere else.
| | 01:23 | So what's the alternative?
| | 01:24 | Well, here are a few sites that I'm a
big fan of. Probably primary and top of
| | 01:28 | the list is developer.mozilla.org.
| | 01:32 | This is one of the best single sources
of information on JavaScript, which is to
| | 01:36 | be expected, as JavaScript really comes from them.
| | 01:39 | Now they have several areas on this
site, but they do have a particular
| | 01:43 | JavaScript section, including
a full JavaScript Reference.
| | 01:47 | There is a JavaScript Guide.
| | 01:49 | There is ECMAScript 5
information. Great, great content here.
| | 01:54 | Similarly, some of the other sites that
belong to browsers such as dev.opera.com
| | 01:58 | also have some terrific articles, the
Internet Explorer Developer Center on
| | 02:03 | Microsoft does as well.
| | 02:05 | If you're using a third-party
library like jQuery or Prototype, make sure
| | 02:09 | that you're making good use of the
site for that library and using its
| | 02:13 | tutorials and its documentation.
| | 02:16 | Similarly, yahoo at
developer.yahoo.com/javascript has a great
| | 02:21 | JavaScript developer center.
| | 02:23 | Now a lot of this is focused on people
who are using the JavaScript libraries
| | 02:28 | from Yahoo, but there is also some
great, great content there, particularly in
| | 02:32 | the developer.yahoo.com/performance
section, which has some great best practices
| | 02:39 | for general web development
and for JavaScript in particular,
| | 02:43 | so definitely worth checking out when a
performance issue becomes something that
| | 02:47 | you're looking at closer.
| | 02:49 | Now for more of a general forum,
Stack Overflow is my preference here.
| | 02:53 | This is a great place for questions and
answers, although make sure you read the
| | 02:57 | entire thread whenever you see this,
because the discussion is usually as
| | 03:01 | informative as the selected answer.
| | 03:03 | But if I even just search on the
term 'JavaScript' here, I could search on
| | 03:08 | JavaScript date calculation or
JavaScript jQuery or what have you.
| | 03:13 | If I order by votes here, what I'm
going to see is a bunch of the most popular
| | 03:18 | posts under the term JavaScript.
So I've got jQuery Tips and Tricks, Hidden
| | 03:22 | Features of JavaScript, What
should every JavaScript programmer know?
| | 03:27 | And again, it's not just the
list, but it's the discussion.
| | 03:30 | It's the amount that get
up-voted and down-voted.
| | 03:33 | This stuff is all really, really good content.
| | 03:36 | So I'm a big fan of stackoverflow.com
as a great question-and-answer location.
| | 03:42 | And last but not least, take a look at
some of our more advanced courses here on
| | 03:46 | lynda.com, and bear in mind, not all of
them will say JavaScript in the title,
| | 03:52 | because you're also going to find
courses on HTML5 and on jQuery, for example,
| | 03:57 | but there is some great, great content here too.
| | Collapse this transcript |
| Goodbye| 00:00 | I hope you've enjoyed this
JavaScript Essential Training course.
| | 00:03 | This was designed to introduce you to
the language, the core syntax of it, how
| | 00:08 | to think about it, write it, start
to debug it, work with the DOM, and
| | 00:12 | introduce you to best practices and the
kind of issues and possibilities you're
| | 00:16 | likely to run into.
| | 00:18 | It's now your job to take some
part of this and run with it.
| | 00:20 | Learning programming languages is
like learning a musical instrument;
| | 00:24 | you can read and watch to learn the
basics, but to get comfortable, there is no
| | 00:28 | substitute than hands-on practice.
| | 00:31 | Now whether you're interested in the
basic JavaScript functionality or going
| | 00:35 | more advanced, going deeper with AJAX,
exploring HTML5, or seeing what the
| | 00:39 | third-party JavaScript libraries can
do for you, you should be in the perfect
| | 00:43 | position to do just that.
| | 00:45 | JavaScript is the most important
programming language on the web, and it's
| | 00:49 | becoming more important as the years go by.
| | 00:52 | This is a fantastic time to
really learn this language.
| | 00:55 | Thanks for watching. See you next time!
| | Collapse this transcript |
|
|