navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

JavaScript Essential Training
Mark Todd

JavaScript Essential Training

with Simon Allardice

 


Use JavaScript to add new features and a richer, more compelling user interface on web pages. This course keeps current best practices and practical uses for JavaScript in mind, while covering syntax, working with the DOM, and developing and debugging across multiple platforms, devices, and browsers. Author Simon Allardice also shows how to progressively enhance and gracefully degrade web pages, and take advantage of the world of JavaScript libraries now available.
Topics include:
  • Understanding the structure of JavaScript code
  • Creating variables, functions, and loops
  • Writing conditional code
  • Sending messages to the console
  • Working with different variable types and objects
  • Creating and changing DOM objects
  • Event handling
  • Working with timers
  • Debugging JavaScript
  • Building smarter forms
  • Working with CSS, HTML5, and JavaScript
  • Using regular expressions

show more

author
Simon Allardice
subject
Developer, Web, Programming Languages, Web Development
software
JavaScript
level
Beginner
duration
5h 31m
released
Jul 22, 2011

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:04Hi! This is Simon Allardice, and welcome to JavaScript Essential Training.
00:08JavaScript is the programming language of the web invented for the web to add
00:13behavior and interactivity to your pages.
00:15We'll begin with the basics: the core of JavaScript language and syntax, how to
00:20write it, where to put it, what tools you can use.
00:24We'll then start to go step by step through the different things you do with JavaScript.
00:28We'll work with forms, work with events, get to really understand the DOM, the
00:34Document Object Model, the way you will understand and change your pages in
00:38reaction to what the user is doing.
00:40You'll see how to debug JavaScript.
00:43We'll also explore the popular JavaScript libraries like jQuery, and we'll wrap
00:47up with some more advanced topics.
00:49And along the way, we'll see a lot of best practices that have developed over recent years.
00:54So whether you're brand-new to JavaScript or perhaps you've been working with it
00:57on and off for years, welcome to JavaScript Essential Training.
Collapse this transcript
What you should know
00:00In this course, I'm starting with the idea that you know some HTML and you know
00:04some CSS, because JavaScript is a language that works with and manipulates
00:09web pages, so I expect you know how to make web pages.
00:13And that even if you use a WYSIWYG design program like Dreamweaver, you could,
00:17if you had to, still open up a text editor and write a basic HTML file with
00:22correctly nested elements.
00:24You don't have to be a guru.
00:25I don't expect you to write a transitional XHTML doctype tag from memory, but
00:30you could make a simple page that works.
00:33And that similarly, with CSS, you're good with creating and applying styles to
00:37elements, working with IDs and classes.
00:40And if that's not the case, take a look at our other courses at lynda.com first.
00:44Now, I don't expect you to be a programmer.
00:47We are going to start from scratch.
00:49Though if you know about programming fundamentals, variables, loops,
00:52conditions, that's very useful.
00:54And of course, if you are an experienced programmer, that's great and welcome.
00:58Be aware that in the next few movies, we're going to cover the core language
01:02syntax of JavaScript, much of which is based on C.
01:05So, if you've spent several years living in C or C# or Java, yes, you're going
01:10to see some things that you already know, so expect that.
01:13JavaScript did not try and invent a new way to write an if statement.
01:17So, you might be tempted to jump ahead, but I do suggest you go through all the content.
01:22Now, I just invite you to relax and enjoy the ride early on, because even in the
01:26initial stages, you're going to see things that are different from what you
01:29expect, even in the most fundamental content, like creating variables and checking equality.
01:35And it's those little differences that the existing programmers need to focus
01:39on, the basic things you take for granted but just don't apply in JavaScript.
Collapse this transcript
Using the exercise files
00:00If you're a Premium member of lynda.com, or if you're watching this tutorial on
00:04a DVD-ROM, you have access to some exercise files used in this title.
00:09I have the folder here downloaded to my Desktop.
00:12It's just a folder called Exercise Files, and in that, you'll find each of the
00:16relevant chapters will have its own folder.
00:19And in some of these folders, there are files that represent some simple assets
00:23that I'll be working with during the movies.
00:25And we'll point those files out at the relevant time by just showing you the
00:29path to the file location.
00:30These are all just for convenience.
00:32They're not required, but they do make things a little easier.
00:35Now if you don't have access to the exercise files, you can follow along from
00:39scratch or just create your own assets.
Collapse this transcript
1. Getting Started
Introduction to JavaScript
00:00So before we start writing some JavaScript, let's get some core concepts cleared up.
00:05It's very common to see JavaScript referred to as one of the three core
00:09languages of web pages.
00:11You have the HTML markup language for content and structure.
00:15What's your headline, how many divisions are in your page, how many paragraphs
00:19do you have, what are the contents of those paragraphs?
00:22Then the CSS, the style sheet language, for presentation.
00:25What font does the headline use, what's the background color of the page, what's
00:29the width of the div that the paragraphs are in?
00:31And JavaScript, the programming language for your behavior and interactivity.
00:37What happens when you mouse over a menu, what happens when you type the
00:41wrong value in a form field, how long does a photo slideshow take to move
00:45from one image to the next?
00:48JavaScript is a programming language that you'll often hear it referred to as a
00:52scripting language, and sometimes you'll hear some software developers dismiss
00:56JavaScript as just being a scripting language.
00:59And what they mean by that is that JavaScript is intentionally limited.
01:03I can't write a desktop application in JavaScript the way I might do with C++ or
01:08Java or .NET or Objective-C.
01:12JavaScript only works inside another application, the web browser.
01:17Whether that's IE or Safari or Firefox or Chrome or Opera, they all have a
01:22JavaScript engine inside them.
01:25The operating system runs the web browser, the web browser contains a page, and
01:29the page contains the JavaScript.
01:32Now another way JavaScript is limited is that yes, it doesn't have access to the
01:36file system of the computer that it's running on.
01:39There are no words in JavaScript to open or save local files because that
01:43would be a security risk.
01:45There are no words in JavaScript to talk to a database or target a USB port.
01:50And that strikes some software developers as odd because most languages are all
01:55about input and output, and JavaScript isn't.
01:58But of course, they're missing the point. JavaScript wasn't designed as a
02:01general purpose programming language;
02:03it was designed to manipulate web pages and it does that very well.
02:07Now as you know, when a user opens their browser and requests a page from your
02:13web site, they're just send HTML and CSS as plain text, and you let their browser
02:19take care of interpreting and rendering it
02:22however their browser wants to, whether it's mobile, whether it's on a laptop
02:26or a desktop, and it's the same with JavaScript.
02:29JavaScript is a client-side language.
02:33It is sent to the user's computer and it runs there.
02:36That's as opposed to server-side technologies like PHP, ASP.NET, Ruby on Rails.
02:42They'll execute their code on the web server and deliver the results to the client.
02:46But with JavaScript, we just send our code to the client and we let them run it.
02:51I'm going to just interject a side note here.
02:54JavaScript was designed to run as a scripting language using a web browser as a host program.
03:00That's why it was invented.
03:02But because it has become so popular, it has in recent years popped up as a
03:06scripting language in other applications, and even in server-side products.
03:10So you'll find it in things like Adobe Acrobat and Photoshop.
03:14JavaScript is in server-side products like Node.js and Google Apps Script.
03:19But in this course, I'm not focusing on those uses of JavaScript.
03:23I'm talking about classic JavaScript, a client-side language used to add
03:28interactivity to web pages.
03:30Now if you're interested in JavaScript for any other reason, use this course
03:33to learn the core of the language, and then you can jump into those other applications.
03:38So back to talking about JavaScript as a client-side language.
03:42One impact of this is that because JavaScript is sent to the client, to the
03:46user, is what if the user has disabled JavaScript in their browser?
03:51Well, then we can send it over, but it won't do anything.
03:53It will be as if the JavaScript never existed.
03:57Now while this situation is less common these days than it used to be, that does
04:01mean we need to do our best to write web sites that will work whether or not
04:05JavaScript is enabled.
04:06But yes, we want to add all of this cool functionality, but if the user doesn't
04:10have JavaScript, the web site still works.
04:13It might have more limited interactivity, but it's still perfectly usable.
04:18Now another issue can be the variety of browsers out there.
04:21Just has different browsers can render and display web pages differently, usually
04:25because they don't handle CSS exactly the same way, what happens if they handle
04:30JavaScript differently?
04:31Well, this was one of the reasons why JavaScript had a bad reputation for a long time.
04:37Go back a few years and a lot of JavaScript had to be written to detect the
04:41browser and handle different browsers in different ways.
04:44And I'm very happy to tell you that's not really an issue anymore.
04:48There are a few edge cases, but typically we don't care what browser the user has.
04:53And to understand why, let's do a super-quick history lesson here.
04:57So JavaScript was developed in 1995 by Brendan Eich at Netscape, and it first
05:02became built into a web browser with Netscape 2.
05:05It was originally going to be called LiveScript.
05:08But because Sun's Java language was the new big deal at the time, Netscape and
05:12Sun had an agreement to rename LiveScript to JavaScript to jump on that
05:17popularity bandwagon of Java.
05:18And most people these days agree this was a bad idea and caused a lot of confusion.
05:24The two languages have nothing to do with each other.
05:26If you're brand-new to programming, they might look a little similar to you, but
05:30that's because they both really look like C.
05:32So JavaScript is not Java.
05:35It is not a light version of Java.
05:37It was not based on Java.
05:39It doesn't matter if you know Java, and we will talk no more on the matter.
05:43Now as it became popular in Netscape, Microsoft then made their own version
05:47for Internet Explorer.
05:49They couldn't call it JavaScript, so they called it JScript, and we had more
05:52browser differences to deal with.
05:54And what happened, thankfully, then was that Netscape submitted the language to
05:58the ECMA or ECMA standards body to create an independent and officially
06:03standardized edition, and they did.
06:06The standardized edition of this language is officially called ECMAScript, and
06:10it was first published in '97.
06:12And really what we're doing in this course is ECMAScript. That's a name by a
06:17committee, so everyone just called it JavaScript, even though Mozilla officially
06:21owned the JavaScript name.
06:22Now ECMAScript has had a few different editions, but the one we care about is
06:28edition 3, which may surprise you.
06:30It was published way back in 1999, but that's the one that you can reliably
06:35assume full support for in every major browser,
06:40and it's the one we're going to focus on in this course.
06:43ECMAScript Version 5 was published at the end of 2009 and adds a few features to
06:50the language, particularly in the advanced area.
06:52But I'm recording this course in mid-2011. ECMAScript 5 is only now
06:57getting some support in the most recent browser versions.
07:00Adoptions of standards like this take years, and yes, at some point in the
07:05future ECMAScript 5 will be the standard, but it isn't yet.
07:09And just to let you know, compatibility was a big deal in development of
07:13ECMAScript 5, so everything we do in this course will be compatible moving
07:17forward and it will also work in all the older browsers for many years to come.
07:21Now if you're wondering what happened to ECMAScript 4 in those ten years between
07:25edition 3 and edition 5, well it just got way out of hand and they abandoned it;
07:30ECMAScript 4 never happened.
07:31Now, one of the benefits of having a standardized language like this is it
07:36doesn't matter if you're a Mac, PC, or Linux person, it doesn't matter if your
07:41server is Windows or Apache, if your backend is PHP or Ruby on Rails or
07:45ASP.NET or ColdFusion or none of the above; JavaScript is completely agnostic on these matters.
07:52There's no special tools required.
07:54There's no licensing needed.
07:56Sure, as with editing HTML and CSS, some applications may make our life a little
08:01easier, but all we really need is a basic text editor.
Collapse this transcript
Creating your first JavaScript
00:00So let's get started with writing some JavaScript.
00:03Well, JavaScript runs in a web page.
00:05That is the container that it needs to sit in.
00:07So step one, have a web page.
00:09I have a very simple HTML file here on my Desktop.
00:13It's about as basic as they come.
00:15I can open it up in a browser here and take a look that it's
00:18really straightforward.
00:19I'm now going to open it up in a text editor, and I'm just going to use TextEdit here;
00:24the equivalent would be Notepad on a PC, but you can use anything you like.
00:28I'll just increase the text size to make that a bit more readable.
00:33And as you can see, it's super basic.
00:35The HTML is just describing the content and structure of a simple page.
00:39We have a headline. We have a couple of paragraphs.
00:43We have an unordered list.
00:44I don't even have CSS on this page.
00:47I'm not worried whether this is HTML Strict or XHTML Transitional;
00:51we're just proving a point.
00:53Well, just as we use opening and closing h1 tags to surround a headline, or
00:58opening and closing p tags to surround a paragraph, I can use opening and
01:02closing script tags to surround some JavaScript.
01:05And we'll talk more about where we should put these script tags in a little bit.
01:09I'm just going to put them after the closing tag for my unordered list.
01:13So I'll do the opening tag, and then I'll do the closing tag, and inside them
01:18the script I'm going to add is simply the classic first program in any
01:22programming language: the word 'alert' written in lowercase, open parentheses,
01:28double quote, the phrase "Hello, world!," closing double quote, close
01:32parentheses, semicolon.
01:34This is one JavaScript instruction, one JavaScript statement.
01:39Now to run it, I simply save this file, and then I'll double-click it to open it
01:48up in the web browser.
01:50And this is all it does:
01:53it pops up the annoying JavaScript alert box.
01:55Now other browsers might render this slightly differently, but the effect is the same.
02:00Yes, this is boring; yes, this is simple; and yes, the alert box is one of the
02:05more annoying things that JavaScript does; but this is where we begin.
02:10Now we need to see how to add some more.
Collapse this transcript
Getting to know the tools and applications
00:00Some programming languages are tied closely to certain development
00:04environments and platforms.
00:05If you tell me you're writing iPhone apps, I'm going to assume you're using Objective-C,
00:10on a Mac, using Xcode.
00:13If you're writing.NET apps, you're probably using Visual Studio on a PC.
00:18JavaScript has no such association.
00:20There is no one true program here, or one true platform.
00:24It's as agnostic as they come.
00:26So when I'm asked what application I'd recommend for writing and editing
00:30JavaScript, my answer is "Whatever you're using already."
00:34If you use Dreamweaver to make your web pages, stay there to write your
00:37JavaScript, or Coda, TextMate, BBEdit, Visual Studio, Eclipse, Komodo, Emacs,
00:43Vi, or whatever, if you know your way around it, stay there.
00:47Every modern web-development or programming application supports
00:50JavaScript editing.
00:52Now for some of this course, I'm going to use Aptana Studio available from aptana.com.
00:58And I'm using this here for two main reasons:
01:00one, it's free; and two, it's available on Mac, PC, and Linux.
01:06I'm going to record this course mainly on a Mac, but that was a
01:09coin-toss decision.
01:10Whatever you're using is fine; the platform is irrelevant.
01:14Now this course does not require Aptana, and I won't be spending time
01:18exploring its features.
01:20I'm just using it here as a simple JavaScript and HTML code editor because it
01:25would be tedious for me to use TextEdit or Notepad all the time.
01:29I want at least line numbers and basic indenting and formatting.
01:33So if you need an editor, check out Aptana; otherwise, feel free to stay with
01:36what you already know.
01:37Now the second set of tools are more important than your operating system, and
01:42more important than even your editing environment: the browser.
01:46This is where your code runs.
01:49Now you may have a favorite browser-- most people do--but there's really no
01:53excuse for not having all the major browsers.
01:55And I would suggest having the latest version of them.
01:58While you can make a case for developing using older browsers to check
02:02performance and backwards compatibility, the benefit of the latest browsers is
02:07that the JavaScript tools get a lot better.
02:10And that's more important to us.
02:12Now Internet Explorer in all its versions still has the biggest percentage
02:16of total browser market share, but Firefox is the most popular
02:20cross-platform browser.
02:22It has great JavaScript debugging tools, and it's what I'll be using most of the
02:26time in this course.
02:28So if you don't have it already, grab yourself the latest stable version of Firefox.
02:33I'm using Firefox 4 right now, which is the current stable release as I was
02:37recording this course.
02:38And you should also go and install-- if you haven't already--the Firebug
02:44extension, which you can get from getfirebug.com.
02:47Now, this is a fantastic tool for just general web development, but one of the
02:52things Firebug allows us to do is experiment with JavaScript directly in the
02:56browser without even creating HTML files.
03:00So I'm going to jump over and install this, find the latest version, which for me is 1.7.
03:09This has point releases quite often, so you're likely to see a different version of it.
03:14I'm going to go ahead and select to install it.
03:17And once the browser restarts, I have Firebug installed. And I can actually turn
03:22it on and off by clicking down here. There's a little bug icon at the lower
03:26right-hand side of the status bar.
03:28And I can just use it to toggle the Firebug panel on and off.
03:31It can also be set to open up in its own window, but I'm going to leave it here for now.
03:36One of the great things Firebug allows us to do is experiment with JavaScript
03:40directly in the browser without even creating HTML files.
03:44I'll get deeper into Firebug later on because it has several useful sections
03:49that I can get to by clicking the links on the panel here, but the one I'm
03:53interested in is the Console one.
03:55Right now, it's giving me a message that the Console panel is disabled, so I'm
03:58going to click the little dropdown arrow here and say I want to enable it.
04:03And it pops up a couple of messages here that it's enabling the JavaScript
04:06debugger to support Console and so on.
04:08You see right down here at the bottom where I've got the three Greater Than
04:12signs, I can actually just directly type in JavaScript and run it.
04:15Just write a statement and hit Return or Enter to execute it,
04:21in this case, popping up an alert box.
04:24However, one line at a time is a little tedious, but over here again at the
04:28right-hand side, I have this little button called Command Editor, and if I click
04:32that, what it's going to do is divide this panel into two pieces.
04:36I can just drag it to resize, and I actually type in as much JavaScript as I
04:40want over here on this side.
04:46I could type several lines.
04:47When I'm done, I come down and click the Run button at the bottom and we pop up that message.
04:53On the left-hand side, we'll see kind of a mirror of anything that we've typed
04:57and any diagnostic messages that it may have given us.
05:00We'll make more use of this left-hand side of the panel later on.
05:03Now this is not by any means any kind of major development environment, and it's
05:08not even going to prompt you to save anything.
05:10So for anything more than a few lines, I'm going to use a full editor.
05:14But for us, experimenting and learning basic JavaScript syntax, it can come in
05:18very handy to just play around with writing code.
Collapse this transcript
2. Core JavaScript Syntax
Understanding the structure of JavaScript code
00:00So as you see, JavaScript is written as plain text, like HTML and our CSS, and
00:06JavaScript is what's called an interpreted language, not a compiled language.
00:10A lot of other languages need to be run through a special program called a
00:13compiler that takes your code, converts it into machine code, which can then run
00:18on the operating system, but we don't need to do that with JavaScript.
00:21We simply write our code and we hand it over to the web browser, and the web
00:26browser takes care all interpreting it and running it on the machine.
00:30Now, JavaScript is case sensitive.
00:32Let me repeat that.
00:33JavaScript is case sensitive!
00:36If you're coming from a case-insensitive language, like Visual Basic or Pascal or
00:41even old-school HTML, you may want to write that down and stick it in front of
00:45your face for a while, because it's really important.
00:48Now this is often a challenge for web designers coming from years of handwriting
00:52HTML, where, okay, it's good practice to be consistent, but really if you open a
00:58lowercase p tag and close with an uppercase P tag, it doesn't really matter.
01:04Well, it matters here.
01:07One will work; the other will not.
01:09Mix up the case in a JavaScript keyword and it will not guess.
01:13It will not assume what you meant. It just won't work.
01:16JavaScript will let you be a little sloppy in some other areas, but case
01:20sensitivity is not one of them.
01:23Now JavaScript code, like in most programming languages, is grouped into
01:27statements, separate instructions or commands to say piece by piece what you
01:31want your script to do, perhaps change the color of the piece of text, calculate
01:36someone's age, move an image five pixels to the left, make a menu option
01:40disappear or appear, or pop up an alert message.
01:44Now what I'm writing here is obviously not JavaScript;
01:46it's what's often called pseudo code, just plain English lines of what I might
01:50want a script to do without worrying about syntax.
01:54A JavaScript statement is typically written by itself on one line. In the same
01:59way that you might use a period or a full stop,
02:02to finish a sentence in English, each JavaScript statement should end with a semicolon.
02:07Now because of this, you can put multiple statements on one line, just separating
02:12each of them with the semicolon, but don't do this--it makes it harder to read,
02:16split multiple statements onto multiple lines.
02:20In fact, what's more likely is the opposite situation where if you have a
02:24really, really, really long statement, you can split that across multiple lines
02:29to make it easier to read, marking the end of the full statement with a
02:32semicolon, but most of the time one statement, one line.
02:37Now, JavaScript is a forgiving language about some things.
02:41That might sound like a good thing, but it really isn't.
02:44If you're familiar with HTML, you know you can forget to close a tag and most
02:49of the time the page would still work, but you know this ends up being a bad
02:54thing, because it leads to sloppy code, and it leads to browsers trying to guess what you meant
02:59and often different browsers doing different things with that guess.
03:02Now the equivalent here is that in many cases your JavaScript statement would
03:07still work if you left off the semicolon, but don't.
03:11Let's just imagine it's required, because if you're casual about it, you
03:15will run into problems.
03:17So we'll always be conscious of using the semicolon to finish a statement.
03:20A JavaScript might be case sensitive, but it's not sensitive to spaces or line
03:26returns between different pieces of the language.
03:28So if I have the statement "Hello world," I could also write it like this with a
03:32lot of spaces between the different pieces of the statement.
03:35I could even split it onto different lines.
03:38You can typically use however many spaces or line breaks make it readable
03:42to you, but the only place spaces do matter is here inside the double
03:46quotes, because it then assumes that we want to write out Hello, space,
03:50space, space world.
03:52But other than this, and other than the idea that you can't put a space in the
03:56middle of a word, JavaScript really doesn't care.
03:58Now as you're writing code, it's useful to add comments, so you can add
04:02comments to your JavaScript by simply typing a line with two forward slashes both together.
04:08This is like other C-based languages.
04:10JavaScript than ignores anything after the two forward slashes and begins
04:14again on the next line.
04:15Now, typically you add comments on the line above the one they're referring
04:20to, but you can also add them at the end of statement as well, and they will be ignored there.
04:25You can also comment out multiple lines by typing a forward slash asterisk, and
04:30everything after that is considered a comment, even if it's a hundred lines later,
04:35until you see the flip side, the asterisk forward slash.
04:37Now I only tend to use this to comment out large chunks of code when testing;
04:43everywhere else I use the single-line style.
04:45It's a bit more obvious.
04:47Now like most programming languages, the default behavior when JavaScript runs
04:51is to start at the first statement and move down, executing each statement one by one.
04:58And the question is, when?
05:00And unless you say otherwise, it's as soon as the browser sees your code, and
05:06that can have very interesting implications, because we can put the script tags
05:12just about anywhere in our HTML.
05:14We can put it in the head section, in the body section, in the middle, but let
05:18me show you the impact of this.
05:20So again, I'm looking at this very simple, very straightforward HTML page with a
05:24little bit of JavaScript in it.
05:25I'm going to cut the script tags from where they were and place them in the head
05:31section, and you'll see this a lot.
05:33You'll see a lot of script tags in the head section.
05:35I'm then going to save this and double-click this HTML file to open it up in the browser.
05:42Now, notice what it's doing here.
05:44The browser is reading our HTML, and it's going line by line through the HTML.
05:50It hits the script tag and is executing this script, this line, as soon as it gets to it.
05:56Now that alert is causing us to pause and as you can see, the page is actually blank.
06:02It's grayed out, but it's completely blank until I click OK, and then we see the
06:06content of the page actually jump in and fill and be rendered.
06:11Now if I take that script tag, cut it from the head, and move it to the end, save
06:18that, run this again,
06:21while we get the same JavaScript behavior, you'll notice that the actual page
06:25content has already been rendered before we then ran our JavaScript.
06:29So the position of your JavaScript in your page really does matter, but by
06:34default it will be interpreted and executed as soon as the browser sees it.
06:39Now, okay, on a simple page like this that's fine, but of course we don't always
06:44want to run everything immediately.
06:46Okay, sometimes we want to run the code when the page loads, but sometimes not
06:50till the user fills out a form, or moves their mouse, or hits the Tab key.
06:55And we'll do that, as in most languages, by grouping our code into separate
06:59self-contained pieces and then telling the browser we only want to run them in
07:03response to certain events, but that's another movie and we've got a couple of
07:07things to cover first.
Collapse this transcript
Where to write your JavaScript
00:00Before we get much further, let's talk a little bit about where our
00:03JavaScript should go.
00:05You see creating JavaScript like this, what's referred to as inline code, is okay
00:09to get us started but is not how we're going to continue.
00:12The problem with having your JavaScript mixed in with your HTML is not an issue
00:17on a tiny test page like this, but when you start creating more complex pages
00:22your code becomes fragmented.
00:24It becomes hard to edit.
00:25It becomes hard to maintain.
00:27And because you often do the same thing across dozens or hundreds of pages,
00:32you've got duplicated code and if you make any changes, you might have to make
00:36them dozens or hundreds of times.
00:38So instead of having it this way, what's referred to as inline JavaScript, we're
00:43going to put our JavaScript in a separate file like you might do with CSS.
00:48It's easier to maintain,
00:49it's easier to use across multiple pages, and as you'll see, it's even easier to write this way.
00:55We simply cut our JavaScript from the HTML and put it in a separate file.
01:00Now we don't need to copy across the script tags; we keep those in the HTML page,
01:05because we need them to describe the link between our HTML page and the
01:10JavaScript. And we just use the source attribute, the SRC attribute, like you might
01:15do with say an image tag.
01:16Now your JavaScript file is just text. It could be any file name, but by
01:20convention it ends with.js.
01:23Now right now these two files would need to be beside each other in a folder or
01:28subfolder, because the SRC, the source attribute, obeys the same rules as
01:32linking to an image or a style sheet file.
01:34This could be a relative link.
01:35It could be an absolute link. It could even be on another server.
01:38In this course, I'm going to tend to keep them in the same folder for
01:41simplicity. And then we can just squeeze up the script tag, because there
01:44is nothing inside it.
01:46Now we have a great division between our HTML and our JavaScript.
01:50Let's talk a little bit more about the script tag itself.
01:53When reading other people's JavaScript, you're going to very often see this type
01:57attribute in your script tag.
01:59And this is saying not only this is script, but this is JavaScript.
02:04Officially, it could be a whole range of different options, and it's hearkening
02:07back to the days when we had to worry about what particular flavor of scripting
02:11language we were using.
02:13But if you leave it off, every browser will assume it's JavaScript anyway.
02:17Now yes, the type attribute is formerly required if you're fully complying to the
02:22HTML 4 or XHTML spec, but in the HTML5 spec it's officially optional and just
02:28defaults to JavaScript.
02:30Now some code editors will add the type attribute automatically, and some others
02:34will complain if you don't have it.
02:36So it might be easier for you to leave it, but I have never encountered a single
02:40situation while leaving it off has any impact at all.
02:43So I'm in the rather large count that says these days just leave it off.
02:47And next question, where do you put the script tag?
02:49It's very common, as we've said before, to see the script tag in the head and
02:55although this will work,
02:56I'm not a big fan of this, because remember JavaScript is parsed and interpreted
03:00as soon as it's hit by the browser, and that means your JavaScript file could cause
03:04a delay in rendering the page.
03:06And we really don't want to slow the page down.
03:08We want the browser to load the page, and then we'll have our script come along at the end.
03:11Now there might occasionally be a need to immediately load and process some JavaScript.
03:17For example, you might be using JavaScript to actually create the page content.
03:22Then okay, you want it as soon as possible. But if there is a good rule of thumb,
03:26it's to have your script tag not just in your body section, but at the very
03:30bottom just before the closing body tag.
03:33Now, if I'm linking to style sheets, I'll keep those links in the head section so
03:38that they do load immediately, but my general rule is style sheets up at the top,
03:42script files down at the bottom.
03:44Now, later we might even have multiple script tags here to link to multiple
03:49JavaScript files, and then we could get concerned about what order they are in,
03:53but we'll cross that bridge when we get to it.
Collapse this transcript
Creating variables
00:00In all programs and all programming languages we have to keep track of many
00:04pieces of data, email addresses, a date of birth, position of an image on the
00:09screen, the current score in a game, so we create variables to hold that data.
00:14A variable is a container.
00:17It's us grabbing a little piece of computer memory and giving it a name, so we
00:22can use it while our JavaScript is running.
00:24We create it, we name it, we put a value in it, and then we change the value as we need to.
00:30In JavaScript, you create a variable like this.
00:33You use the word var, all written in lowercase, which is part of the JavaScript
00:38language, and then the word you want.
00:40The name of the variable itself is up to us, and it should represent the piece of
00:45data that we want to hold, in this case year, but it could be customerEmail, or
00:49todaysDate, or while we're experimenting, just nonsense words like foo, or even
00:54single letters like x.
00:56The name that you want to use for your variable must be written as one word, no
01:00spaces are allowed, and it can be made of letters, numbers, the underscore, and
01:06the Dollar sign, but you can't start with a number.
01:10So, for example, a variable with the name 99problems would not be allowed, but a
01:15variable with the name problems99 would be allowed.
01:19Now we'll talk more about naming our variables and what you should call them
01:23later on when we talk about style in JavaScript.
01:26I'm just going to use simple names for now.
01:29So what we're doing with this line of code is we're just carving out a little
01:34area of memory to hold a value.
01:36And right now after this line var year runs, this variable exists.
01:42It has a name, year, but it doesn't have a value. It's regarded as undefined, and
01:46undefined has a special meaning in JavaScript.
01:50Now there is no real point in having a variable that stays undefined,
01:53so we can define, or set, the initial value of the variable when we create it.
01:58We could do that as two statements: first, var year to make the variable and
02:03then year = 2011 to set it.
02:06Now the equal sign here is setting the variable to the value 2011.
02:11It is an instruction.
02:12Now, more typically if you're doing this, you just combine these into one
02:17statement, var year = 2011, to both define it and set its value.
02:22Now here is another place where JavaScript will let you be sloppy and I
02:27won't. Technically, the word var is not even required.
02:32In JavaScript, if I write some script that starts off with this line, JavaScript
02:36will go looking for an existing variable called year, but if it doesn't find it,
02:41it will just make it.
02:42However, we are always going to use var when defining our variables.
02:46There are a couple of situations where leaving var off can lead to unexpected
02:50behavior, so make a habit of always using it.
02:53Now variable names are case sensitive so var x with lowercase and var x with
02:59uppercase would be two different variables.
03:01Now you can run into problems accidentally sometimes here.
03:04Let's say we create a variable called x lowercase and set it equal to 200, and
03:09then later in our code we just want to change it to 210.
03:12Well, if I accidentally use an uppercase X here, I've got a problem: because
03:17of the automatic creation of variables from JavaScript, we now end up with two different ones.
03:22And now nothing would give you an error, and nothing would inform you that this is happening.
03:27So be careful when naming your variables.
03:29Now if you're creating multiple variables at the same time, instead of
03:33spreading them across multiple lines, you can create one JavaScript statement
03:38and just separate the names of the variables with commas, and that would give
03:41you three variables here.
03:44Similarly, if you're creating and initializing them with these initial values,
03:49you can separate those with commas as well to both create them and set them.
03:55So just by running that one line, we get an area of memory allocated for us with
04:01the name that we chose.
04:02Now, in many other programming languages when you define a variable, you don't
04:06just give it a name, but you also have to say exactly what type of information
04:11is going to be stored in each variable. Is it an integer? Is it text?
04:15Is it a Boolean value, which just means a value that's either true or false, and so on.
04:20Now once you've chosen the type you're not allowed to change it, but in
04:24JavaScript we don't do that.
04:27JavaScript is what's called a weakly typed language.
04:30We don't make an integer variable, or a text variable, or a Boolean variable.
04:35We just use var to create a generic variable and then simply put whatever type
04:39of value we want in it.
04:41So if I executed the line var myVariable, I actually begin with this as undefined.
04:47If I then say myVariable = 200, that variable stores the number in it.
04:52If I say myVariable = Hello and the word Hello in double quotes here, this is a
04:57piece of text, what's referred to as a string, and that just means one or more
05:01characters strung together.
05:03Now with JavaScript, you can use either double quotes or you can use single
05:08quotes to surround a string of text, but just don't mix them. Don't open with
05:13double quotes and close with single quotes.
05:15I tend to use double quotes because that's more common in other languages, but
05:19you'll see both ways. And we can store Boolean values, which is just a value that
05:24can either be true or false.
05:27Now with these you do not need the quotes around them.
05:30JavaScript understands the words true and false written in lowercase.
05:34They are considered part of the JavaScript language.
05:37So you can start a variable off as undefined, then put a number in it, then a
05:41string in it, then a Boolean in it.
05:43That doesn't mean JavaScript doesn't care about the type of data you have--it does.
05:48It treats numbers differently from strings and strings differently from Booleans,
05:52but any JavaScript variable can hold any of these values, and more complex data
05:58too, including arrays and objects and even functions, and we're going to go
06:02deeper into how they all behave later on.
06:04And as you'll see, sometimes you'll need to ask, "Well, what kind of value is in a
06:09particular variable?"
06:10Now of course, the point of making variables is that we're going to use them.
06:15We're going to manipulate them, ask questions of them, but that all begins by
06:19knowing how to make them.
Collapse this transcript
Working with conditional code
00:00Beyond the most basic JavaScript one-liners, we need to start asking
00:04questions, being able to have code that only runs under certain conditions
00:08rather than all the time, and we begin this with the classic if statement, found
00:13in any programming language, written in JavaScript, as in other C-based
00:17languages, using this format.
00:19We have the word if, and then we have a condition inside parentheses and
00:24then if that condition is true, we will execute whatever code is inside the braces here.
00:30Now a quick aside for the folks new to programming.
00:32Yes, in programming languages we are really picky about the symbols we use and
00:37about what we call them.
00:38So just to be very specific, when I say parentheses, I mean these; when I say
00:42brackets and I usually say square brackets, I mean these guys; and when I say
00:47braces, and I'll usually say curly braces, I mean these.
00:50Now, they serve similar purposes, to mark where something starts and where it
00:56finishes, but they are not interchangeable.
00:58Now all of these are always found in pairs.
01:01If you have an opening one, you will need a closing one.
01:05It may be several lines later, but it needs to be there.
01:09So back to the if statement.
01:12So in this case, the parentheses are used to mark out whatever our condition is,
01:17and the curly braces area used to mark out what we'll do if that's true, which could
01:22be one JavaScript statement, could be a dozen, could be 100.
01:24Now whatever the condition is, whatever we are asking, whatever is in the
01:29parentheses here must evaluate as true or false.
01:33So if I have a variable called a and I want to see if it's less than 50, I
01:38don't care what it is.
01:40I don't care if it's 49 or -5 million or 50.0001; all I want to know is is this
01:47true or is it false?
01:49Is a less than 50 or isn't it?
01:52Is b more than 20 or isn't it?
01:54All conditions must boil down to simply true or false.
01:58Now, if I have a variable called c and I want to check that it's equal to
02:02something, to check equality in JavaScript, as in other C-based languages, I can
02:07use the double equals sign.
02:09There is no spaces between them. Double equals is considered a single operator. Now heads up,
02:15even for the programmers, JavaScript has another way of checking equality,
02:20the triple equal sign.
02:21We will come back and talk about equality again, but realize for now that if, in a
02:27condition, if you're asking if something is equal to something else, you will
02:31never use a single equal sign.
02:33As we saw with variables, a single equal sign is an assignment. It's a command.
02:38It sets a value, not checks a value.
02:41So we can use double equals or right now triple equals will do the same thing.
02:44Again, we'll come back to this one. And if I want to check that a variable is not
02:49equal another value, it's the exclamation mark and equal sign,
02:53in this case checking that the variable d is not equal to 100.
02:57If that's true, we will execute our code.
03:00When you have several statements surrounded by these curly braces, this is
03:05what's referred to as a code block, and this is all the curly braces do.
03:09They group a section of code together.
03:12They don't have any other meaning than that. And as you will see, these blocks can
03:16be nested the same way, say, in HTML you can nest divs inside other divs.
03:21Now a quick word about curly braces.
03:23When reading other people's code, you're likely to see them occur in a couple
03:26of different styles.
03:27I'm jumping across to Firefox with Firebug here where I have my little
03:32JavaScript window open, and I'm declaring a variable called amount and setting it
03:37equal to 500, and then I have my if statement here.
03:40If amount is less than 1000, that needs to be either true or false, then we will
03:45execute whatever's between the opening and closing curly braces.
03:50Now the opening curly brace right now is right after the condition, and that's
03:54probably the classic way that you'll see these for C and C++ programmers.
03:58You might also see the braces on separate lines so that they line up.
04:03People get religious about brace styles.
04:06JavaScript of course does not care.
04:08This is regarded as insignificant white space, and it doesn't change the
04:12meaning of the code.
04:13The most commonly in most sample code you will download or you will find
04:17online, you will see it this way,
04:19immediately opening the brace after the condition but closing it on its own line.
04:23If I decide to run this, not surprisingly, I should have the pop-up box here
04:27saying it's less than 1000.
04:29Now if you have an if statement and you only want to then execute one line of
04:35code, technically you don't need to put the braces in.
04:40You don't need to define a code block for one line, but it's good practice to
04:45always do it, because if you miss it off, it's really easy to mess things up if
04:50you decide to edit this code later, so always use the blocks.
04:53And we will always be using these code blocks, even if we only have one
04:58JavaScript statement within them.
05:00So if this code is executed when the condition is true, well, what happens if it isn't?
05:03If we just leave it like this, nothing.
05:06It would skip over the if and begin on the next line. But if you wanted
05:09something else to happen, you can follow the if with an else statement and in
05:15this case have another code block that runs different code.
05:18If the first condition is true, we run the code in the first block; otherwise, we
05:22run the code in the second block. And you can even nest them inside each other
05:27and check a different condition.
05:29But don't nest too deep.
05:30JavaScript can handle this quite fine, but lots of nested ifs, say even beyond two
05:35levels, is quite difficult to read and make sense of.
05:37If we do have to have more complex logic, we are going to start breaking things
05:41apart into their own functions.
Collapse this transcript
Working with operators
00:00Just about every statement we will write is going to involve an operation,
00:04moving data from one place to another, adding, subtracting.
00:07Now to perform a lot of these operations we need operators, and that just means the
00:12symbols that we are using to manipulate our values.
00:15The most obvious are probably the arithmetic operators.
00:19We have addition, we have subtraction, an asterisk for multiplication,
00:23forward slash for division.
00:24Now you typically see these used along with the equal sign, and the equal sign is
00:29formally called the assignment operator.
00:32When we hit the statement we are going to execute whatever's on the right of
00:35the equal sign and use it to assign of the value to whatever is on the left of the equal sign.
00:41So for those of you who are new to programming, remember that when you see a
00:44single equal sign that's not a polite description; that's a command.
00:48We are setting a value. We are assigning.
00:51Now you will often see the same variable being used on both sides of the equal sign.
00:56In this case, we are just adding 10 to the variable called score and storing the
01:00result back in score.
01:01Now adding to a variable or subtracting to a variable happens so often that
01:06there is actually a shorthand for this.
01:08I could write the statement this way.
01:10I could also write it this when using the plus equals operator, meaning add this
01:15number to this variable.
01:17Note that this is a single operator, so there is no spaces between the plus and
01:20the equals. And if we have a shorthand for adding to a variable, we also have a
01:25shorthand for subtracting a number for a variable and for multiplying or
01:29dividing a variable by a particular number.
01:32Now as with most languages, there is operator precedence in JavaScript, simply
01:38meaning some operator symbols are treated as more important than others.
01:43Particularly multiplication and division are regarded as more important than
01:47addition or subtraction.
01:49So, if I read the expression on the right-hand side of the equal sign and just
01:53read it in order, left to right, I would think 5+5 is 10 times 10 is 100, but
01:59no, the multiplication is regarded as more important, so that's done first.
02:035 multiplied by 10 is 50, then we add 5, and the result is 55.
02:08If I want to impose an order on this, I simply take the important pieces that I
02:12want to be executed together and surround them with parentheses.
02:16In this case, I would take the 5+5 and that would make sure that that was
02:21executed independently.
02:23Then we multiply it by 10, and the result is 100.
02:26And moving on, we have the comparison operators, back to this idea of equality.
02:32Again, if you're checking that variables are equal to each other or equal to
02:37other values, you can use the double equals operator.
02:40Now a classic mistake of programmers in any C-based language, including
02:46JavaScript, is to accidentally use a single equal sign where you meant to use
02:50a double equal sign. So here is an example.
02:54I create two variables, variable a=5, variable b=10.
02:57If later on in my code I ask if a=b? Well, I am using the wrong operator.
03:05What's going to happen here is that the single equal sign is a command.
03:08We will hit this, and then we will set a=b. This then returns true, and the code
03:15in the if statement will always be executed, even when you think it shouldn't be.
03:19This is perfectly legal syntax in JavaScript and in a lot of other languages
03:23too, but it can lead to code that just doesn't work the way you expect, and it's
03:26difficult to debug because it's easy to miss.
03:28So remember one equal sign is assignment. You are telling.
03:34Two equal signs is the equality operator. You're asking.
03:38And in JavaScript, there is another equality operator, the three equal signs.
03:45Three equal signs is the strict equality operator.
03:48Now what on earth does that mean?
03:50Let me show you an example.
03:51I am going to open up Firefox.
03:53I just have my preferences set to open on a blank page, and I'll open up the Firebug panel.
03:59Make sure I am in the Console and that I have the whole right-hand pane
04:04activated, so I can type some JavaScript in here.
04:07You can also do this in an HTML page or a JavaScript file.
04:14So I write some very simple code here.
04:16In this code, I have two variables.
04:18Variable a starts off with the number 5 and variable b starts off with the value 5 but
04:24as a string, using double quotes.
04:27Now I am going to go ahead and run this.
04:30So I'm checking if a is equal to b. And if you notice I must be popping up the
04:36alert that says, Yes, they're equal.
04:38And here's what's happening. If I use the two equal signs as the equality check here, they are regarded as equal.
04:46The JavaScript engine is checking them and saying okay, these two variables may
04:50not be identical, one is a number and one is actually a string value, but they
04:55have the same value, so I am going to say this is true.
04:58But if I use the three equal signs here, this is strict equality check.
05:03Run that again and the output here is that they are not equal.
05:07The comparison is false.
05:10Three equal signs, strict equality, is going to check that they're the same value
05:15and that the same type under the hood, that they're not just equal, but identical.
05:19Now most of the time the double equal sign and the triple equal sign will behave the same.
05:25As an example, if I had created the second variable just to have the number 5, then if
05:30we use the three equal signs, we would say, yes, they're equal and if we use two
05:35equal signs, yes, they're equaled.
05:37They are both equal and they are identical.
05:38Now most of the time you will find that the double equals and triple equals
05:44could be used interchangeably, though some JavaScript experts recommend using
05:49the triple equal sign all the time and just never using double equals.
05:52I wouldn't go that far, so when I see a double equal sign in someone else's
05:56JavaScript I don't consider it wrong. But if you were to get into the habit of
06:00using triple equals all the time, that's certainly not a bad habit to get into.
06:04So when we are writing, say, an if statement and we're checking if we have
06:08equality, double equals. If we want to check that something is not equal to, it's
06:13the exclamation mark equals, or we have the triple equals and its
06:17counterpart exclamation mark equals equals, not strictly equal to.
06:23We then have the classic greater than operator, less than operator, greater than
06:27or equal to, less than or equal to.
06:30And again, all of these must respond with either true or false.
06:36Something is equal or it is not; something is greater than or it is not;
06:41something is strictly equal to or it is not.
06:43Now what happens if you have a few questions to ask?
06:47If in a situation that we are comparing several things, I want to know if a is
06:52strictly equal to b and c is strictly equal to d, how do I write that?
06:57Well, what we will use here is the double ampersand.
07:01This means "and," a logical "and."
07:03And I say logical "and" there because some people take "and" as meaning addition.
07:08The flip side of this is what if we are interested in one or the other situation?
07:13If the variable a is strictly equal to the variable b or the variable c is
07:18strictly equal to the variable d, we use the double vertical bar, or pipe symbol.
07:25This is the logical or.
07:26Now you will often see these kind of split up with multiple sets of parentheses
07:31to make it a bit more explicit about what you're looking at,
07:34in this case, if a is greater than b and c is less than d. But as ever, the entire
07:41condition, the wider set of parentheses must evaluate as either true or false.
07:48If you have several things to check, you may even split it across multiple lines
07:52if you want to make it more readable.
07:54It's one of the benefits of white space being insignificant.
07:57Now, a couple of roundabout operators here.
08:00We have the modulus, or remainder operator in JavaScript.
08:05This one's a little different. Probably the classic example here is using it to
08:09do something like calculating a leap year.
08:11So in this case I create a variable called year, and it's equal to 2003, and then
08:17I create a variable called remainder.
08:19I set that equal to year % 4.
08:23The % here is the modulus, or remainder operator.
08:26What it means is divide the variable year, 2003, by 4, but don't give me the
08:32result, give me the remainder, which in this case 4 would go into year 500
08:37times and the remainder would be 3, and you will run into this one now and then.
08:42Next, we have shorthand for adding to a variable.
08:46Now we have already seen this a little bit.
08:48If we have a variable called a and we want to add 1 to it,
08:51I could do it the long way, which would be this.
08:54I could do it the shorter way, a+=1.
08:57But if I am just interested in adding 1 to a variable, I can also use another
09:02operator, which is ++.
09:04If you want to get geeky about this, this is what's called a unary operator,
09:08meaning it only needs one thing to act on.
09:11Now the plus plus operator, which increments by 1, can be used either after the
09:17variable name or before the variable name,
09:19so a++ or ++a. And the flip side is true.
09:24We have a=a-1, or a-=1, or a--, or --a, they all do the same thing. Now by themselves
09:34on lines like this, great.
09:36But there is actually a tricky difference.
09:38So the plus plus and the minus minus can be used either before the variable name or after.
09:44Technically, if you want to get geeky about it, it's what's called the prefix
09:47and postfix versions of those operators.
09:50And while they end up doing the same thing, they do it in a different way, and
09:55there is an impact to which one you choose.
09:57Let me show you what I mean.
09:58Let's say we start off with creating a variable a and setting it equal to 5.
10:04What I am then going to do is write a statement that says alert(++a).
10:10So I want to pop up a message box with the contents of the variable a, and I'm
10:14going to add 1 to it.
10:16What happens is using the prefix version where the plus plus is before the
10:20variable we will actually execute that, and we will increment a before we run this line.
10:27So the value of a will be changed to 6 and then the alert message will pop up saying 6.
10:34However, if I go back and do this a slightly different way, doing an alert with
10:39a++, what happens is we will first do the alert and only then, at the end of the
10:46line, will we cause 1 to be added to a.
10:49The end result is the same, that the variable a=6, but the message that we popped
10:55up was different, and this is one of those little things that can cause bugs.
11:00So I tend to only use the plus plus and minus minus on their own statements by themselves.
11:05Then it doesn't matter.
11:07I know that when I have executed that line of code it's been incremented or decremented.
11:12And finally, the last one that I am going to talk about is a great little useful
11:17one called the ternary operator.
11:19That's not a great name, but there is no better name for it.
11:22See, most of our operators are what are called binary operators.
11:25Now it doesn't mean they work on binary code.
11:27It just means they work on two elements;
11:29there is something on the left and something on the right, a+b, amount divided by year.
11:35They work on two pieces.
11:37The unary operator, plus plus, minus minus, works on one, and ternary works on three.
11:43So it actually has two symbols to it, the question mark and the colon.
11:48Now the general format of using this is that you have a condition.
11:52You're asking something.
11:54Then you say what happens if this is true and what happens if this is false.
11:57You can actually think of it as a mini if/else statement.
12:01So let me show you an example here.
12:04So let's say I define two variables: var playerOne=500, var playerTwo =600.
12:09Now some time later in my code I want to create a high-score variable and I
12:16want to set this equal to whatever the larger of the first two are.
12:21Well, I could write this using an if statement.
12:24If playerOne>playerTwo, we will set highScore=playerOne; otherwise, we will set
12:29highScore=playerTwo.
12:31So I have got about six lines here just to set the value of highScore.
12:36With the ternary operator, it would let me take it from six or seven lines to one.
12:41What we do is we specify three things: the condition, question mark, what if it's
12:45true, colon, what if it's false.
12:47So my condition is playerOne>playerTwo.
12:51Like all conditions, this has to be either true or false.
12:54I put the question mark. Then I say if it's true, I want to return the value of
12:59playerOne colon, if it's false, I am returning the value of playerTwo, semicolon
13:06to end the statement.
13:08This would allow me to get rid of that if statement and have the whole thing just on one line.
13:14Now we probably won't use this much in this course, but you will see it from time to time,
13:18so I want to be able to recognize it when you do see it. And this has given us
13:22plenty of operators and definitely will be enough to get us moving and building
13:25some useful logic in our code.
Collapse this transcript
Sending messages to the console
00:00I've been using this alert box because we need some way of getting a message out
00:05of JavaScript, but it is kind of annoying, particularly if I have several of them,
00:10because it requires that I click the OK button to dismiss it. And it's certainly
00:14not going to be what we want to do much more except in real alert circumstances.
00:19But luckily, we have Firebug, and having Firebug gives us something very useful here.
00:26Instead of alert, from now on what I'm going to do when I want the same
00:30equivalent is I am going to change that to console.log, leaving everything else the same.
00:35This is all written in lowercase.
00:38As you can see, I have three statements here that all call console.log.
00:42Now if I run this one again, instead of having the alert box pop up in the
00:46page section, I'm actually getting a pop-up over here in the actual console,
00:51which is part of Firebug.
00:53Console.log is not officially part of the JavaScript language.
00:56It's an add-on that Firebug is bringing to the party,
00:59although it does work in other JavaScript debuggers like the ones you can get in
01:03Internet Explorer and Safari.
01:05Now what that does mean is that unlike an alert message, if you don't have the
01:09Firebug console open, you are not going to see it, but that's okay.
01:13It's intended for us as writers of JavaScript; it's not for the end user.
01:18They should never see it, but we certainly want it.
01:21So we can write out a string as a message to the console.
01:25We could write out a variable like the variable I have defined just a step
01:28above, which is foo.
01:30I can write down multiple variables just by separating them with commas, and over
01:35on the left-hand side I am just going to hit the Clear button to clear the
01:38console, run this again, and I can see the output that I'm having here.
01:42Now, a log message is just a log message.
01:46This could be a good message, could be a bad message, could be informative.
01:51We can make that behavior more apparent if we know there's an error, or we know
01:55it's informational, by changing the word log to one of four other words.
02:00We could change log to debug.
02:03Now I will just comment out the other lines right now.
02:07Clear the console on the left and run it.
02:09Not much of a difference on that one.
02:12Change debug to info.
02:15Now I get the little I icon here.
02:18Change info to warn.
02:21Now I get the yellow and the exclamations mark. Or change console to error and run that,
02:28and we actually get the error message here.
02:30It's the same message, but different icons for them.
02:33Though note, if you do have an error, you will also now get it in the status bar
02:37as well, but for the most part we will just be doing console.log, the most
02:43straightforward way of doing this.
02:45We can do a few other things with the console, as we'll see later, like
02:49measuring performance and how long a script is taking to run, but if nothing
02:54else, console.log is going to come in immensely useful for us to understand
02:57our own code better.
Collapse this transcript
Working with loops
00:01Very quickly we will find ourselves writing code that we want to have happen
00:04multiple times. Whether that's grabbing every paragraph in a page so we can
00:10change the background color of it, hiding everything in a menuing system,
00:14we will realize there's code we want repeated.
00:17Well, rather than write it out multiple times, I'd rather write it once and be
00:21able to say, "Repeat this five times," or "Repeat this 5,000 times," or "Just keep on
00:27repeating till I tell you otherwise,"
00:30perhaps go through every single form field on the web page or process every link
00:36on a web page in some way, and this is what we do when we are creating loops.
00:41You will also hear this referred to as iteration.
00:44The main issue with any loop is not when to loop--looping is easy--it's when to stop.
00:50If we need to loop 200 times, who is keeping track?
00:53If we need to loop until we are told to stop, where is the code to figure out how to stop?
01:00But let's first figure out the most basic kind of loop.
01:03Well, we've seen if statements before, and this is all I have here.
01:06If this condition is true in the parentheses, we will execute the code
01:11inside the curly braces.
01:13Now if all I do here is replace the if with the word while, we have a loop.
01:18It could be a one line in this code block, there could be 100 lines in this code block;
01:24whatever is in the block gets done every time the loop goes around.
01:29So we start to run this code.
01:30We will create a variable called a, set it equal to 1.
01:33We will come down to this while part.
01:36I will check the condition, which in this case is a < 10. Yes, that's true.
01:40I'll jump into the body of the block,
01:42execute any lines of code that are there.
01:45We will hit the end.
01:46We will hit the closing brace, and that will jump as back up to the while
01:50statement again, where we will ask the same question, is a < 10? Well, yes it is.
01:55It's still 1, in which case we'll continue on processing.
01:59What we've done here is create a loop.
02:02We have actually created an infinite loop, which isn't all that pleasant. It's a bad thing.
02:07This would never end. a is always going to be less than 10 because we never change it.
02:12So a very common thing that we need to do in most loops is make sure that
02:17whatever we are doing to keep track of the loop is being incremented.
02:22So this time I've got an a++ at the end of the body of the loop.
02:28So with the of the iteration in place, we will start to increment a every time
02:31we go around the loop, and we will keep on going.
02:34And at some point, what's going to happen is a will be incremented to 10.
02:39We will come back to the while.
02:41This will evaluate as false, and then what we'll just do is we will jump out of the loop.
02:47We will jump right to the end, and we will continue processing whatever
02:50code happens afterwards.
02:51Now there is a variant of the while loop called the do while loop.
02:58What this does is keeps the same basic format, but we actually move the
03:02condition to the end.
03:04So instead of while a is less than 10 being at the start of the block,
03:09it's actually at the end of the block, and because of that, we actually need a
03:13semicolon at the end of the do while.
03:15Now the big difference with this is if you have a do while, the block will
03:20always be executed, at least once, even if we started off by setting the variable
03:26a equal to 100. And our condition here is asking while a is less than 10, we are
03:31going to execute the do block once before we even check the condition.
03:35So it will happen at least once. To let you know, while loops are much more common
03:41than these do while loop, and the code I have written over the years I guess
03:44that I write at least 100 whiles for every do.
03:48In most loops it's expected to check the condition before entering the loop, and
03:52it's more readable that way too.
03:53Now in many loops a pattern emerges. If I look at a while loop here, I could
04:00have a lot of stuff going on in this loop, but I always have to have several
04:05pieces in place, regardless of what I am doing.
04:09For a start, I need to have something that keeps track of where I am in the
04:13loop, so very typically, before we hit the while loop, we will create an index
04:17variable or a counter variable. In this case we will call it i--i is a very
04:21common name for an index.
04:23So we set up the index, or the counter.
04:26We then have to have a place that checks the condition,
04:28how do we know whether to keep going through the loop or not, and then in most
04:32cases we have to increment the index at the end.
04:35So regardless of what we're doing, we need these three pieces in place.
04:40Set up the index, check the condition, increment the index, and this is so common
04:45that there is even a shorthand way of doing this,
04:48a thing that brings all these together, the for loop.
04:53With this, you actually bring those of three pieces together inside the parentheses.
04:59They are all there at the top.
05:00So regardless of what's in your loop, again it doesn't really matter.
05:04Whatever is between the braces will be executed, whether it's simple or complex,
05:08but the loop itself has three pieces.
05:11We set up the index, so in this case var i=1. Then there is semicolon. Then we
05:18check the condition, i is less than 10, and then, even though it's right at the
05:22top, this is the incrementer. This happens at the end of every loop.
05:27Now we don't have to go up by 1.
05:29You could go up by 4 or 17 or 150 every time if you wanted.
05:32So this is very readable because everything about the loop is right there at the top.
05:38You don't have to look outside the loop for the index, nor scan inside the
05:42loop for the increment.
05:44So the for loop is a very common way of doing this.
05:46Now, next up is a couple of words you'll occasionally run into, not as much as
05:52the whiles and the fors, but it's worthwhile knowing about them,
05:55a word called break.
05:58Break is a word that will jump us out of the loop.
06:02So let's say we start running our code and we hit this loop.
06:04We hit it for the first time through.
06:06We set up the index equal to 1.
06:08We run the check. Is that less than 5000? Yes, it is.
06:11We start to move through the code.
06:13We will hit this if segment, for example, and it will say is i=101? No, it isn't.
06:18So we will skip past that code block and continue on, hit the end of the
06:23loop, go back up, check the condition again, yes, i is still less than 5000, continue on.
06:30Now, at some point what's going to happen is i will be 101. We will hit break.
06:34As soon as we hit break, we are basically manually saying we are done.
06:39We jump completely out of the loop, and we continue on, regardless of what the
06:43condition was at the top, regardless of where our counter was. If we say break,
06:47we are done with the loop.
06:51And continue is along the same lines but not quite as drastic.
06:56Let's say in this loop, however I've got it set up,
06:59I've got some pieces of code.
07:01We are doing some stuff. We are checking some options.
07:03We are doing a second set of stuff.
07:05Well, as we move through the code, if I check this if statement and my counter
07:10divided by 5 leaves a remainder of 0,
07:12I'll hit that continue; but if it isn't, I will just jump straight ahead and
07:16keep going on the second part of the loop.
07:19Now at some point again we will jump back.
07:21We will check it, we will start processing, but if ever at any point I actually
07:25hit the word continue, that doesn't mean jump out of the loop;
07:29it means jump back up and check the condition again.
07:33Don't continue any further with this iteration, just this one.
07:37We are not done with the entire loop, but we are done with this time around.
07:42So we jump right back up, check the condition again, and then start to process.
07:46So continue moves us back up to the top.
07:49Break moves us out beyond the bottom of the loop.
07:52Now, you won't need continue or break in most loops, but you will see them from
07:57time to time, and you need to know what they mean.
Collapse this transcript
Creating functions
00:01As we start to add more code, we want to make sure that it doesn't get messy and
00:04hard to read, so as with all languages, we are going to break apart large amounts
00:09of JavaScript into smaller reusable modular pieces.
00:14All we are doing is taking several statements, wrapping them up, and giving them
00:18a name, and that means we are creating functions.
00:21In other languages, these might be called modules or subroutines, but in
00:25JavaScript it's functions.
00:28To make one, we take the code that we want to enclose--
00:31this could be one line, it could be a hundred lines--
00:34we surround it with curly braces to create a code block to say where this
00:38function starts and ends.
00:40We need to say what this is, so we actually use the JavaScript word 'function
00:43all lowercase, and because we could have dozens or hundreds of these, we also give it a name.
00:49This part, like variables, is up to us.
00:52The name has to be one word.
00:54There can't be any spaces.
00:55You can use letters, numbers, Dollar sign, and underscore, but you can't
00:59start with a number. And the function name should simply be descriptive of what it does.
01:05I will just be generic right now. And then after the name of the function we
01:11need to have opening and closing parentheses.
01:14These say whether this function expects to have data passed into it, and in this
01:18case empty parentheses means no, it doesn't. Now after the function is declared,
01:24then we can call it.
01:26Sometime in our code we can use the name of the function with the opening and
01:30closing parentheses, semicolon--because it is a full statement--and all the code
01:35in the function will be executed.
01:38We could do it again. We could do it again.
01:39Now, note that as soon as you put your code in a function, it won't execute.
01:46It won't run unless you explicitly call it.
01:50Now as you start to write files of JavaScript, you'll end up having a lot of
01:54functions, and it doesn't officially matter where you put them in your file,
01:59because the JavaScript engine will first do a quick scan of your code and figure
02:04out what functions exist before it tries to run anything.
02:07But it's a best practice to define your functions before you call them.
02:11So in this case, for example, I have got the first line of code saying
02:14myFunction, but myFunction isn't declared till afterwards, which then calls
02:19myOtherFunction, which itself isn't declared till after that.
02:22It's a better practice to rearrange them so that functions are defined and
02:27declared before you use them.
02:30You don't have to, but it makes for more readable code.
02:33Typically, that just means you are going to define all your functions up at the
02:37top of your JavaScript file.
02:38It's very common to create functions that expect parameters,
02:43they expect to be passed information.
02:46Now to do this, we take our parentheses and we put our parameters in there.
02:52We say how many pieces of information are going to be passed and what do I want to call them?
02:56We don't need the word var.
02:58I am just saying here I expect to be passed one piece of information and I am
03:02going to call it x. So in the code inside myFunction, I will have this variable
03:07called x that I can play around with.
03:10Or if I want two, three, four, parameters, I just separate them with commas.
03:15You call them whatever you want.
03:16It's the same rules as variable naming.
03:19So defining a function that takes X,Y means that inside the code I can just
03:25treat X and Y as if they exist, in this case making a new variable from them.
03:31Whatever is passed in I will multiply together, and then I will log out the result.
03:36And then again later in the code I can call this function. First off, I am
03:40passing in two number. Then I can call it again, pass in a couple of
03:43different numbers, and so on.
03:46Now if the format looks familiar, that's because we're using this when we use
03:50that alert, or we when we use console.log.
03:53Alert is a built-in function in JavaScript.
03:56It takes a long piece of information;
03:58in this case, we are passing in a string.
04:01And we can optionally return values.
04:03Not only can the function accept information, but we can also send some back, and
04:10you can do one or the other, or both, or neither.
04:13If I want to return the information, all I use is the word return and then
04:18pass back a variable, or a literal, like a string literal in double quotes, or a
04:24number--it's up to you.
04:26Those of you who come from other programming languages might think, "Well, surely
04:29the function has to be defined differently if we return a value," and in
04:33JavaScript, no it doesn't. This is all we do.
04:37You don't have to return anything from a function. It's up to you.
04:39Now what this format means is that later on I could use this function to
04:45create a result. And in fact in the last line here, I am creating a new
04:49variable and setting it equal to whatever is returned from passing in the numbers
04:546 and 9 into my function.
04:57Now if a function does return a value and you don't do anything with it, you are
05:00just calling the function. That will just be ignored.
05:03Now one of the usual issues with functions that take parameters is what happens
05:10if you get something wrong with them?
05:11What happens if you pass the wrong amount of information in there?
05:15Let's say we have a function defined called calculateLoan.
05:17This takes four parameters--amount, months, interest, and name--and it presumably
05:21does something with them inside the body of the code.
05:24The way that we should call it is just by passing those four parameters in order,
05:31and inside our function, when it runs, we will have amount equal to 10,000, months
05:35equal to 60, interest equal to 7, and name equal to Sam Jones.
05:40Now if I call myFunction and I pass in an extra parameter here, in a lot of
05:46other programming languages this would break your code; in JavaScript it
05:50will just ignore it.
05:51That extra one we drop off the end. We are effectively just running the
05:54function just fine.
05:55And the flip side of that, what happens if I pass in too few parameters?
06:00What will happen is that the missing one will be passed as undefined.
06:06interest and name in this case will be undefined variables.
06:10Now your function code might be able to deal with that, and it might not.
06:15So it doesn't necessarily mean it will work, but this is what will happen.
06:19And one last thing, we are going to talk about something called variable scope here.
06:23Now, scope of a variable simply means where is this variable visible?
06:28What part of your code can see it, what part of your code can use it?
06:31So, I have got a function declared here called simpleFunction.
06:35It has got some code in it, and then we have a line that declares a variable foo=500.
06:41We then have console.log foo and if we call this variable, it's going to
06:46output 500 to the console.
06:48But let's say right after I call this variable, I then write another line of
06:53code that says console.log(foo), and then I run console.log(foo), trying to write
06:58out the contents of that foo variable.
07:01I know this function has already run, so surely I can write it out. But no, what
07:05I get here is the message undefined because outside the function, as far as
07:10JavaScript is concerned, foo doesn't exist.
07:14That's because when we use the word var inside a function definition, this
07:19creates a variable that's known as a local variable.
07:22It only exists and is only relevant inside the function itself.
07:28If I needed to have a variable that was visible throughout my entire file of
07:32code, what I'd do is I would declare foo outside the function.
07:37This now becomes what's called a global variable if it's declared at the absolute
07:41top level and outside any function that you have.
07:45Then what I need to do inside the function is I don't need to define it again, so
07:48I am not using a word var.
07:50foo can be set to 500.
07:52We can write it out inside the function, and we can write it out outside the function.
07:56Now, usually when you're declaring variables inside a function, you only want to
08:01access them inside the functions,
08:03so using var is absolutely fine, but just be aware that you have this concept
08:07of local variables with functions. And for those of you coming from other
08:12languages with variable scope, know that this is only relevant with JavaScript inside functions.
08:17This doesn't apply to other code blocks like loops and if statements and so on.
08:22It's a very simple split.
08:24You use var inside the function,
08:26it only exits inside the function; otherwise, it's available everywhere.
Collapse this transcript
3. Types and Objects
Working with arrays
00:00So we've seen how to create variables.
00:02We use the word var, we give it a name, and then we can use the equal sign
00:07to give it a value.
00:08That could be a number, that could be a string, that could be a Boolean.
00:12What we can also do is create arrays.
00:15An array is a single variable that holds multiple values.
00:20You create it quite similarly to creating a normal variable.
00:23I'm going to make one here called multipleValues.
00:26You can call it anything you'd like.
00:28But to tell JavaScript this is an array, there are a few ways to do it, but the
00:31easiest one is this:
00:33var multipleValues = opening square bracket, closing square bracket.
00:38And this is the indicator that we're dealing with an array.
00:41When you see the square brackets, it's a pretty good indicator you've got an array.
00:46This line simply creates a single variable called multipleValues that you can put
00:52several things inside.
00:53Well, how do you do that?
00:55Using the square brackets again.
00:58If we want this array to hold multiple values, we need to be able to say which
01:02one are we dealing with, so we use an index.
01:05And I'm saying here I want the index at 0 to be equal to the value 50.
01:10I want the index at 1 to be equal to the value 60.
01:13I can say the index of 2 is equal to the value Mouse.
01:17And notice that what I can do is I can put in a number,
01:20I can put in a string,
01:22I could put in a Boolean;
01:23it doesn't matter what kind of data you're putting in at the different slots in
01:28the array, but all of them are accessed through the index.
01:31That's whether you're setting these values,
01:33that's whether you're getting these values.
01:35And arrays in JavaScript use what's called a zero-based index.
01:38The first entry is at position 0, not position 1.
01:42And that's very common with most languages.
01:45What we can then do is use the same format to get to the contents of the array.
01:50So if I want to write out a console.log message, I want to get the value that's
01:54at position 2 in the array called multipleValues,
01:57I use the square brackets and it writes out the word Mouse.
02:00So if this is the way that we write arrays, it's okay.
02:04It's not too bad, but it would be nice if there was something a little quicker,
02:06and in fact there is.
02:07There is a shorthand method for doing it.
02:10We use the square brackets and we just load it up with those initial values,
02:15in this case, 50, 60, Mouse, inside double quotes.
02:19And it will automatically put them in at position 0, position 1, and position 2.
02:24You could then come along and add on position 3, position 4, and so on, but it's
02:29always a zero-based index.
02:31Now, although this is my favorite way of saying to JavaScript, "Hey, I'm creating
02:36a variable that should be an array,"
02:38there are actually multiple ways to write this, and there's multiple ways you'll
02:41see it when you're reading other people's code.
02:43An equivalent way is this: var multipleValues =.
02:47We use the word new and Array, Array with an uppercase A here.
02:51Now for those of you coming from other languages, you might be familiar with
02:54this kind of format.
02:55That's because arrays are objects.
02:57They are a special kind of value that we're going to have a lot of dealings with shortly.
03:02And although this format saying = new Array will work, you don't have to
03:06even have the word new.
03:08You could just say this as well. All of these are exactly equivalent to each other.
03:11Now for those of you coming from other languages, you might be wondering what is
03:16the size of the array, how does JavaScript know how big this array is?
03:19Well, we can officially create it with a size/
03:23In this case, I'm saying the array should have 5 slots, 0-4, but all arrays in
03:28JavaScript are dynamic.
03:29They can be as big as you want them to be.
03:32If you want something to exist at position 5, you simply load it into position 5.
03:36If you want it to exist at position 100, you load it into position 100.
03:40While there is a theoretical fixed limit to the size that an array can get to,
03:45you're never going to run into to it.
03:47So my favorite way is just the square brackets by themselves.
03:51I think that's the most straightforward way of doing it.
03:53Now because arrays are objects, they have properties, and properties means
03:59information that we can get to about them.
04:01So if I write a line of code that creates an array and loads it up with some
04:06initial values, as in this case, what I can actually do is use the name of the array--
04:10in this case multipleValues--then a dot, and then I can access the length property--
04:16it's information about the array.
04:19So in this case, I can write out a message that says the length of this array is 5.
04:23We have five elements in it.
04:25Now, the highest index might be 4.
04:27We're going to 0, 1, 2, 3, 4, but there are five elements in there. The length is 5.
04:32And because arrays are objects, they also have methods.
04:35Now what does that mean? Well, we know how to call a function.
04:39We use the name of the function,
04:40we use the parentheses, and optionally pass in any parameters that function requires.
04:45Well, a method is a function that belongs to an object.
04:50So if we've created an array or created another kind of object, as we'll see
04:54shortly, we can use the name of that object, then a dot, then the name of the
05:00method to call a method. Here's an example.
05:03So I create an array with five values in it.
05:07I've got this object and it's called multipleValues.
05:10What I can then do is say the name of the object, dot, and then the name of the method.
05:15It's like a function that belongs to it.
05:17Well, arrays have built-in methods.
05:19We've got reverse as one of them.
05:22In fact, when I call reverse on this array, what it's going to do is give
05:26me another array, and I can use the result of that to actually create a new variable,
05:31in this case var reversedValues, which is also an array.
05:35So.reverse() is a method of the array object, as is.join(), which would join two
05:41together, as is.sort(), and I call them all using this dot operator.
05:46But by calling.reverse(), I have this new reversedValues array, and I could
05:51actually call the methods of it.
05:53So I could write out console.log ( reversedValues.join() ) which is a method of
05:58array, and that will actually join all the values in the array together and
06:02output them as a single string,
06:04in this case, writing the contents of it, which are the reversed values, back out.
06:09These are obviously very simple examples.
06:11We'll actually see some practical ones as we go forward.
06:15But the fact that arrays are objects just means we can ask them to do things,
06:19and very useful things in a lot of cases.
06:21If you're new to programming, you might be tempted to think of arrays as being
06:25esoteric things you're not really going to use all that much.
06:28Well, arrays are everywhere in JavaScript.
06:31You won't be able to get away from them.
06:33You may create some yourself, but a lot of them you'll be given.
06:38You'll have to deal with them.
06:39For example, you might at some point want to write a little line of JavaScript
06:44that says, "I want to know how many anchor tags exist on the page, how many links
06:48do I have, or how many paragraphs do I have, or how many h3s do I have?"
06:53Well, what we can do to get that is called the
06:55document.getElementsByTagName method.
06:59And we'll get into this a little later.
07:01We haven't seen it yet.
07:02But this is a built-in ability of JavaScript to scan through our HTML, grab, in
07:09this case, everything that has an a tag, an anchor tag, and return it to us.
07:14I could also ask for all the paragraphs, so all the p tags, or all the h1 tags, or h2s, or h3s.
07:19And what I'll get when I call this is an array.
07:24So whether there are four links on the page or a dozen or a hundred, I'll have
07:28an array to deal with.
07:30So whether you're asking, give me all the links that exist on the page, or you're
07:34wanting to go through all the form fields that exist on a web form, arrays are
07:39going to be your friends.
07:40You are going to have to deal with these.
07:42They are zero-based in JavaScript.
07:44They are dynamic, meaning that you can change them very easily.
07:48You don't have to use special code to do that.
07:51You're always going to see the square brackets to deal with them.
07:54That's always that identifier to you that you're dealing with an array.
Collapse this transcript
Working with numbers
00:00Working with numbers comes easily in JavaScript.
00:03We've already done this. We can create variables and put numbers in them.
00:08And like any language, we have the notion of numeric variables,
00:12we have the notion of numeric literals.
00:14In this case, just the value 200 written in your code is a numeric literal.
00:18But if you're coming from another programming language, you're likely to be
00:21thinking, "What kind of number is this. What kind of variable is this?
00:25Is this an integer, is it a floating- point number, what kind of number is it?
00:30We don't have to ask those questions in JavaScript because internally all
00:34JavaScript numbers are 64- bit floating-point numbers.
00:37That's how they're stored under the hood.
00:39So you don't concern yourself whether it's an integer or a small integer or a
00:44large integer and so on.
00:45Now if you're familiar with floating- point arithmetic, you'll know that you can
00:49have issues with that.
00:51In practice, that doesn't tend to be a problem in JavaScript because most people
00:55aren't really doing complicated financial calculations in client-side code.
01:00But yes, JavaScript numbers are floating-point numbers and all the usual
01:04rules apply to that.
01:06But if you want to store something in a JavaScript variable that has something
01:09after the decimal point, you simply write it.
01:12No special formatting is needed. It's very easy.
01:15However, there are a couple more things we need to talk about with numbers.
01:18One thing that you need to be aware of is just the behavior that happens when
01:22variables have certain values in them.
01:24So let's say we start off with a couple of variables here, var foo and var bar,
01:28both equal to the number 5.
01:31I can tell it's the number because there's no quotes around it.
01:34And we write out console.log. It's foo+bar.
01:36We will write out, not surprisingly, the number 10.
01:40If on the other hand, we say var foo = 5 and var bar = 5, these are strings.
01:45They're surrounded in the double quotes, or the single quotes will work too.
01:49The console.log message, while it looks exactly the same, the Plus sign is
01:54going to do concatenation.
01:55It's just going to slam these two together because it thinks you want to
01:59treat them as a string.
02:01Now, sometimes you do. Say, for example, that these are holding area codes and phone numbers.
02:07You might want to concatenate them together instead of adding the numeric values together.
02:12But just be aware of that behavior.
02:14More likely you're interested in what happens in this kind of situation.
02:18What happens if one of them is a number and one of them is a string?
02:21Well, in this case it's going to do concatenation.
02:23If any part of it is a string, it's going to treat the whole operation as a string.
02:27But that can lead us into more significant issues.
02:30What happens if one of these variables is a string and we're trying to do
02:33something with it that just doesn't make sense?
02:35In this case, we're trying to do console.log(foo*bar).
02:40We're using the asterisk.
02:41So 5 multiplied by b, well, what's that going to do?
02:44Well, actually, what it's going to do here is evaluate as NaN--
02:49that's an uppercase N, lowercase a, uppercase N--which is "Not a Number."
02:53This is a special meaning in JavaScript.
02:56It's telling me here this expression did not make sense, and sometimes we need
03:00to know this, because think about this situation.
03:02Here's the situation we might be more concerned about.
03:05Let's say we know we're going to get a variable.
03:07Now it should be equal to a number, in this case 55, even though that's a string.
03:11But it could be abc, it could be a word, it could be some text, perhaps we're
03:17asking the user for some input.
03:19We hope they type a number, but what if they don't? Well, step one is what I try
03:23and do is I try and make a new variable, in this case myNumber, and create that
03:28by calling the function Number and passing in this variable foo.
03:33Now this function Number is built into JavaScript the same way that alert is
03:37built into JavaScript.
03:38We pass it something and it will try and convert it to a number and return that value.
03:43Now if it can't convert it to a number, let's say this was abc,
03:48it will return "Not a Number."
03:51But I need to know if that was the case.
03:53I need to know if the variable myNumber is not a number,
03:57and luckily, we can check that.
03:59We have another built-in function that we can ask, which is isNaN, isNotaNumber.
04:04Now again, it's the odd casing here.
04:08Is is lowercase, uppercase N, lowercase a, uppercase N. In this case, we pass in
04:13the variable myNumber and the isNaN function will return either true or false.
04:18Now, be very careful about what it's doing here.
04:21We're asking if it is not a number, so it return true if it's not a number.
04:26And we can write out the message, "It's not a number!"
04:29And what's often the case is you're actually more interested in knowing that it
04:33is a number, and we don't have isNumber function, unfortunately.
04:37Well, I could of course just write an else statement after my if and then
04:41process some code there, but if I want to directly ask, what I'll do is phrase
04:45this as kind of a double-negative here.
04:47What I'm asking is if NOT NotaNumber is true, and I'll do that by
04:53calling isNaN function with the exclamation mark in front of it.
04:58So if isNaN returns false, we'll use the exclamationmark to flip
05:04that to true, and then we say console.log( "It IS a number" ).
05:07Yeah, you've got to love programming.
05:08And finally, something that's coming very handy with working with numbers is
05:12something called the Math object in JavaScript.
05:15This is an object that's just available to you, has some very useful behavior,
05:20some useful functionality you can just tap into.
05:22Well, how do we use it?
05:23Well, let's just say we start off by creating a variable called x that's equal
05:27to 200.6, and I want to round that number.
05:30What I can do is just type this code.
05:32I'll create a new variable and set it equal to Math, and we use the word Math
05:36with an uppercase M, .round, passing in the value x. And that's going to round it
05:42to the nearest number. In this case, it's going to be 201.
05:44So what you'll see is a lot of Math. abilities.
05:49We have things like Math.max, which we can create multiple variables, pass in two
05:55or three or four or five, and it will just return the biggest one.
05:59Flip side of that, Math.min.
06:01And the Math object has a lot of these options.
06:03We have Math.PI, Math.random, Math.sqrt, Math.log.
06:08Useful functionality and useful behavior for working with numbers.
Collapse this transcript
Working with strings
00:00So as we've seen, to create variables that are string values, you simply
00:04surround your word or your phrase with double quotes.
00:07Single quotes work as well.
00:09What you can't do is mix them up, can't have an opening single quote and a
00:13closing double quote.
00:14That can lead to issues if you need that punctuation actually inside your string.
00:18So for example, the phrase "Don't mix your quotes inside single quotes" is not
00:23going to work because the second single quote there will be perceived as
00:28closing the string.
00:29We could of course put that inside the double quotes because we're not now mixing them.
00:34We're opening and closing the string on the double quotes alone.
00:37Problem can be if you want to have both of them inside your string.
00:42So in this case, the string itself should contain both double quotes and single quotes.
00:46If that's the case, what I have to do here is I have to escape the double quotes
00:51that I need to be used inside the string.
00:53The way that I do that is just surrounding them with a backslash and then
00:57telling JavaScript these are not intended to close the string, and they will be
01:01considered just fine within the wider opening and closing double quotes.
01:06Now, strings can be treated as objects, and what that means is they have
01:10information we can ask of them.
01:12They have properties that we can look at.
01:13If I create a variable with this simple phrase in it then I can use the name of
01:18the variable, in this case phrase, and a dot, and I can access the length
01:23property, find out how long is the string?
01:25How many characters is the string?
01:27In this case, it's 24.
01:29That's because, in a sense, strings can be treated as arrays of characters,
01:33and the same way we have a .length property of an array, we have a .length
01:37property of a string.
01:38Well, not only do we have properties, we also have methods.
01:42We have things that these string variables can do if we ask them.
01:46So again, creating a variable called phrase, I use that variable name phrase and
01:50a dot, and I can call methods like functions of the object.
01:55So phrase.toUpperCase, which will return, not surprisingly, the entire
02:00string all uppercased.
02:01I also have.toLowerCase.
02:04We have methods like Split.
02:05This will allow us to take a longer phrase and pull it apart.
02:10It will actually create an array from our string.
02:13So I use the variable named phrase.split, pass it a parameter--I'll talk about
02:18that in a second--and that will return an array into the variable called
02:22words, an array of words.
02:24Now, what we're passing into the Split method is a space, just using the double
02:29quotes, space, double quotes.
02:32That means I want to split this string apart at the space, because it's
02:38not always a space.
02:39Say I have some comma-separated values.
02:41I might call split and pass double quote, comma, double quote, create an array
02:47and split them apart on the commas.
02:48So this creates us an array that is 5 elements long, 0, 1, 2, 3, and 4, and
02:54notice that the last word, phrase, also includes the period at the end of it.
02:59But Split can be a very useful method, as can indexOf.
03:03This allows us to find out if a particular term or word appears anywhere in the string.
03:09So again, with a simple string variable, I can call indexOf, passing in the term
03:15that I'm looking for, which of course has to be another string here, and it will
03:18return the position of which that string is found, if it's found it all.
03:22So 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:32store that result in a new variable called position.
03:34If the term that you're searching for is found right at the start, it'll return 0.
03:38Now, the question is well, what happens if that is not found at all?
03:42Sometimes that's just as important, if we need to know this term is not found.
03:46Well, what that'll do is return -1.
03:49So I could say put that in an if statement, if phrase.indexOf, pass in DDDD
03:56is equal to, again using the double equals, which will be exactly the same as
04:00triple equals here, -1, then we can do a message saying, That word does not occur.
04:06We called indexOf.
04:07We passed in the term. It said -1.
04:10It doesn't exist there.
04:11Now, indexOf finds the first occurrence of that term in the phrase.
04:17If it could occur multiple times and we want the last one, we can also ask for .lastIndexOf.
04:23Next, the same way that we have Split to split a string apart into an array, we
04:29also have the method called Slice;
04:31to allow us to slice out a particular piece of that string.
04:34So I am going to begin with a simple phrase and I'm going to store that in a
04:40variable called Phrase.
04:42And what I can do is now call phrase. slice, and pass in two numbers, in this
04:48case 6,11, and that is the starting position and the ending position.
04:53So what this will do is count six positions into that phrase variable, again,
04:59treating the string as an array of characters so we starting at position 0, and
05:03it will grab from position 6, up to, though not including position 11, because
05:09we are grabbing five characters, from 6 to 11.
05:12And it will return that value into the new variable called segment.
05:18Now although it might sound like it should, slice does not change the original string.
05:23So we have a copy of those letters, but the first string remains unchanged.
05:27Now there are actually a couple of other methods in JavaScript that do very
05:32similar things, such as .substring, which in normal usage is basically
05:37identical to slice, and .substr that sounds very similar but the only
05:42difference is that instead of taking a start position and end position, it
05:47takes a start position and a length.
05:49Just the number of characters to return.
05:51And you can use whichever one makes most sense to you.
05:55And finally, a couple of things to be aware of with string comparison.
05:58If we have two strings that are exactly the same thing, then we can use the
06:02double equals or the triple equals to match them, but our string comparison here
06:06is case sensitive, so right now if I have Hello with an uppercase H and hello
06:11with a lowercase h, they will not be considered equal to each other.
06:15If you're worried about that kind of thing, the easiest thing would be to call
06:18toLowerCase, or alternatively, toUpperCase on both of them, if you were at all
06:23unsure that there might be a casing difference in there, and then I can check
06:27them against each other.
06:28Now something you might also be concerned about is the sort order.
06:31What happens if I use the less than or greater than?
06:34Let's say we start off with two strings:
06:36aardvark and beluga.
06:38If I want to ask, is String 1 less than String 2, this works just fine.
06:42It's going to compare beginning with the first letters, and it's going to say
06:45yes, A is less than B, so that will return true.
06:48Well how about the case where I, for example, use an uppercase B?
06:53And I'm wondering is aardvark less than Beluga with an uppercase B?
06:57Well, in fact, this case will return false.
07:01Now it might sound a little weird, but because of the rules of sort order, all
07:05the uppercase letters are considered less than all the lowercase letters.
07:10So in this case the lowercase a of aardvark is considered to be greater than the
07:15uppercase B of Beluga.
07:17Again, something you could solve by just converting both of them into either
07:21lowercase or uppercase so that case sensitivity is not an issue.
07:24Now if you're brand new to strings, I wouldn't at all expect you to be
07:27remembering every single part of this.
07:30The important thing of any programming language is to figure out how do you
07:33remember what those methods do and what properties you have?
07:36So just do be aware that you want to have a good JavaScript reference guide, and
07:41as good as any is actually the reference guide that you'll find at
07:44developer.mozilla.org, and these are the guys that actually own the term
07:49JavaScript, so they know what they're doing here.
07:51At this JavaScript Reference Guide what you'll find is information about things
07:56like arrays, about numbers, about strings, about some of the other stuff we'll
08:00cover later in the course.
08:02And jumping into the string information, you'll find information on getting the
08:06length of the string, individual characters, comparing strings, all the methods
08:10that you might find are useful.
08:12We couldn't really go through all of them and wouldn't want to, here.
08:15Having a reference guide bookmarked is a very useful thing with JavaScript, as
08:19with any programming language.
08:21You don't want to try and commit this all to memory.
08:23You want to know where it is and find it when you need it.
Collapse this transcript
Working with dates
00:00Unlike many other programming languages, JavaScript doesn't have a lot of
00:04built-in objects for us to try and remember.
00:07It has the Math object we can directly use.
00:09It has an Array object.
00:11One of the others is the Date object.
00:13This is how we make a new date.
00:15Now, while you could of course just make several variables to hold a year,
00:18month, and date yourself, this one is a bit more useful.
00:21So we use the var today--pick your own variable name--equals the word new and
00:26Date, with an uppercase D and using parentheses.
00:29Now, if you don't pass any parameters, you'll get it returned with the
00:33current date and time.
00:35Notice that, it's not just the date; it's the time.
00:37It's actually the time down to the millisecond.
00:39Now, you don't always want a date object that exists for today.
00:43So you could create another one which is a new Date and then passing in
00:48year, month, and day.
00:50But notice month is 0 based like an array; it goes from 0 to 11.
00:56The year is the real year, the day is the real day 1 through 31, but month is 0 based here.
01:01You can also get it down to, in this case, seconds, year, month, day, hours,
01:06minutes, seconds if you want to be very specific.
01:08Internally, a date object is stored as the number of milliseconds since the 1st
01:14of January 1970, which is a pretty common way of doing it in the programming world.
01:19Once you have a date object, like having an array or like having a string, you
01:23can do things with it.
01:25We have a lot of methods of the date object that begin with the word Get.
01:30So after creating a new object, I can say today.getMonth and it returns 0 through 11.
01:37I can say today.getFullYear to give me the four-digit version.
01:42That one is not 0 based, so it would return 2011, 2012, and so on.
01:47There is actually a today.getYear, but that one is officially deprecated,
01:52meaning that it would work, but you're not supposed to use it anymore.
01:55The recommended one is getFullYear.
01:58We have today.getDate.
02:00Now, for those of you coming from things like SQL, that might sound like
02:04something that should return the full date, but no. Here that will actually
02:07return you the day of the month, and it's 1 through 31, as opposed to
02:12today.getDay, which would return 0 through 6 for the day of the week and 0 is the Sunday.
02:21An example of using this is if I define say a new Date, and here I'm doing a
02:25date that is 1906, December because we're 0 based for the month, and the 9th.
02:30That's actually Grace Hopper's birthday or Grandma COBOL.
02:33So I'm going to then write out console.log, give it a string, then a comma, and
02:46then I will call myDate.getDay(), opening and closing parentheses just to say
02:53I'm passing no parameters there.
02:55I then close the parentheses of the console.log call and finish the
02:59statement, rerun that.
03:01Apparently, Grace Hopper was born on a Sunday, and simple silly example there,
03:06but that's how you start to get into the deeper parts of the Date object.
03:11We even have today.getHours.
03:14This one is also 0 based, 0 through 23, and there's today.getTime.
03:18Now, this one will actually return the milliseconds since the 1st of January 1970.
03:24Now, that sounds like it's a little bit esoteric, but in fact getTime is one of
03:28the most useful methods of the Date object, and you'll probably see it used
03:33quite a lot, because it's a very direct way to figure out, is something less
03:38than something else?
03:40If one date is less than other one,
03:42I don't have to bother comparing years and months and days, if I can just get
03:47the big number that represents the milliseconds.
03:50Now conversely, we have all these Get methods.
03:53We also have Set methods.
03:55So where we have getMonth, we also have setMonth where we can pass in the
03:59number of the month,
04:00set for year, setDay to manipulate those dates.
04:04Again, you can find the full description of these in any online
04:08JavaScript reference.
04:09One thing we'll often have to do is compare dates, and this does not work the
04:13way most people think it does.
04:15Let's say I create two new date objects.
04:18I'm setting them both here to the 1st of January and the year 2000.
04:22Again, we're passing a 0 for the month, because the month is 0 based here, and
04:25then I ask, is date1 equal to date2?
04:29And I'm using the double equals here.
04:31Now, this would actually respond as false.
04:34Now, as whether I use double equals or triple equals, that's not the problem here.
04:38The problem is is the dates are object, and they're a bit more complex.
04:42What JavaScript is doing is looking at and going, are these the same object?
04:46Well, no, they're actually not.
04:48They may internally have the same values as we're concerned, but it's not going that deep.
04:53It's realizing there are two different objects and saying this is false.
04:56We need a simpler way to compare them, the way that we can compare say
05:00numbers, which is very easy.
05:02So what I'll do instead is I'll ask if date1.getTime--
05:06that's that really useful method that just returns milliseconds--is equal to date2.getTime.
05:12Now, calling both of these are just going to return milliseconds.
05:16It would be like comparing two numbers, and this would return true.
05:20Now you can also use this very easily with comparisons such as greater than, less
05:25than, greater than or equal to, less than or equal to.
05:28So this is one of those areas where the methods of the Date object come in very
05:31handy indeed if you don't want to have to manually start comparing year parts
05:36and month parts and day parts.
Collapse this transcript
Working with objects
00:00So JavaScript does have this idea of objects, although if you're used to formal
00:05object-oriented programming languages, you'll find it very basic.
00:08It has a few very straightforward ideas about what makes an object, and we've
00:12already been doing it.
00:13If we make an array, that's an object.
00:15If we make a date, that's an object.
00:18These objects are self-contained pieces.
00:20If I have an array, I can use the dot operator to say I'm interested in
00:24its .length. In this case it would be 5.
00:27If I have a date, I can call methods of it.
00:29Again, these are functions that belong to an object.
00:32So I can say getTime or getFullYear, and as soon as we start touching our
00:37web pages, we'll have other objects that represent all the different pieces
00:41of the page, what's referred to as the DOM or Document Object Model, and we
00:47can even make our own.
00:48So we're going to get comfortable working with objects.
00:51And at its core, the idea of an object is really simple.
00:55It's just a container that gathers together some data and some behavior.
00:59So we know how to make variables.
01:01We know how to make functions.
01:03An object just allows us to gather variables and functions that belong together
01:07and give them a name.
01:08So let's say here I'm making some regular variables:
01:11playerName, playerScore, playerRank.
01:13It's just creating those three in memory.
01:17And I realize that really these belong together.
01:20It would be nice if I could enclose them in a larger object.
01:23Now, I could do this in an array, but I don't really want to have to worry about
01:27the 0, 1, 2 whole idea.
01:30So what I'll do instead is I'll run this line.
01:34First off, I'll say var player--again, I'm still creating a variable--equals new Object.
01:40This creates me a generic object container and calls it player.
01:45What I then do is just decide, what do I want the internal pieces of this object to be?
01:51So in this case, player.name = "Fred", player.score = 10000, player.rank = 1.
01:58So when we do this our data is now one level deeper.
02:03It's inside this player object.
02:05So we use what's called dot syntax to say this object dot this variable.
02:10Although officially speaking, when they're outside an object we call them variablesm
02:14when they're inside an object we call them properties.
02:18A property is really just a variable that belongs to an object.
02:21Now, because it's quite useful to do this, the same way that there is shorthand
02:25for creating arrays, there is also a shorthand for creating an object.
02:29I create a new variable--
02:30I'll call it player1-- and I use the curly braces.
02:33Now, here I'm not using them to surround a if statement code block or in a while loop.
02:38This is a shorthand for creating an object.
02:41And then inside the curly braces I use this name value pair, in this case three
02:47sets of information: name: "Fred," score: 10000, rank: 1
02:54and it creates the object and those properties inside it.
02:59And then I could just do another line of code and create player2, use the same
03:03format, but create a different object with different properties.
03:07And in this fashion I could get to player1.name, I could get to player2.name,
03:10player3.name, and so on.
03:12So if we create a couple of objects, it's very easy to then write out information
03:17about each individual object.
03:19In this case, we'll write out console.log(player1.name).
03:23That reaches inside the object and writes out Fred.
03:26But it'd be nice to do a bit more to this.
03:28What I'd also like to do is associate some behavior with these objects, not just
03:33some data, not just some information, but what can player1 do?
03:36What can player2 do?
03:37What would be nice is if we could create a function called say playerDetails and
03:43that one I'll just put a comment inside this right now that this should display
03:47information about each player.
03:50Now sure, what I could do is just define this function independently and
03:54declare it as accepting a parameter, but I'm not going to do it that way.
03:58What I'd like to do is make this function part of these two objects.
04:03And the way I need to do that is to associate it with the objects themselves.
04:07What I'm really doing here is making this a method of my objects.
04:11So what I'd like to be able to say is say player1.showDetails or
04:15player1.logDetails and have it call this function. I am associating this
04:20function with this object.
04:21And it's completely up to me how I want to do this.
04:24I'm going to say player1.logDetails.
04:27You might think, well, where that this come from?
04:29I'm just making it up right now, and I'm setting it equal to playerDetails, which
04:33is the name of the function.
04:35I'm not calling it here.
04:37I'm not calling that function at all.
04:39I'm just associating it with my player1 object.
04:42And similarly, what I want to do is exactly the same thing with the player2 object.
04:48So what does this do?
04:49Well, now both of these objects actually have a method called logDetails, and if
04:55we call it, it will just reach through and call the playerDetails function.
04:59Okay, so what. What will it do?
05:01Well, I'd like to actually, let's just do a console.log message here,
05:06information about the player.
05:08If I think, well, I want to write out the name of the object, but I don't know
05:12whether I'm going to be doing player1.name or player2.name.
05:17I just want to do one at a time, and I could call this for either.
05:20Well, here's the thing that we do.
05:22If I know this function is going to be associated with different objects, what I
05:27can use is the word this to refer to the current one.
05:32So whatever object it is, I'm going to go into its name property, or its score
05:36property, or its rank property.
05:38So I'll put together a bit more of a message, this.name and a little string has
05:43a rank of, and then we use the concatenation and just to make it clear I'll
05:49split it across a few lines, this.rank.
05:58Close the console.log parentheses, close the semicolon.
06:01Now, right now if I ran this code, nothing would actually happen, because I've
06:06defined the function, I'm creating the objects, but we don't have any
06:08information coming out.
06:10What I can do sometime later in the code is finally call the logDetails function
06:16of player1 and the logDetails function of player2.
06:19And we're going to use the parentheses to let JavaScript know, yes, we're
06:22actually calling it now.
06:23So I'm going to go ahead and run this, and we get the message out here, Fred has a rank of
06:291 and a score of 10000.
06:31Because it's calling it on Fred, it's jumping and saying, "What does
06:34this logDetails do?"
06:35Oh, well, it calls playerDetails, and that's this function here, which for the
06:40current object, this.name is Fred, this.rank is 1, this.score is 10000.
06:46And I could just call that for the second object, and then we get the second
06:55message out, which is that object's information.
06:58For those of you coming from more formal object-oriented languages, you're
07:01almost certainly recognizing that JavaScript seems very casual about this.
07:05There's not a lot of rules being enforced here.
07:08And yes, that's true. We can just kind of go ahead and make these objects and tie functions to them.
07:13It all seems quite loose and flexible.
07:15Well, that's JavaScript for you.
07:17And know that JavaScript doesn't have formal classes as other object-oriented
07:22languages do, but you can emulate the same effect using a normal function and
07:26something called a prototype, but that's not necessary for us right now.
07:29So I'm going to leave it until later on in the course. Because most people most
07:34of the time don't need to get really deep into object orientation, this will be
07:38more than enough to get us started.
07:40Because knowing this, knowing that the idea of objects, the idea of properties,
07:45the idea of methods, allows us to move on and start working with the really
07:50important objects in JavaScript, the window object and particularly the document
07:55object, the most important object for any JavaScript developer.
Collapse this transcript
4. Understanding the Document Object Model
What is the DOM?
00:00So we've been focused completely on the JavaScript language for these past few
00:04movies, and that is a great way to start with JavaScript.
00:07But of course it doesn't run in a vacuum.
00:10Our scripts will be attached to a web page, and it's the web page that comes first.
00:15They bring our script with them, not the other way around.
00:18So our page, whether a simple page or a complex one, is the canvas that we're painting on.
00:23It's the environment we're affecting.
00:25It is the world that we live in. And we must be able to reach from a JavaScript
00:29into these pages and cause these pages to reach back into our script.
00:33We do that by understanding the DOM, the Document Object Model.
00:39I consider knowing your way around the DOM to be the single most important skill
00:44for a JavaScript programmer to develop.
00:46But this is a term that's often a little tough to understand the first time you
00:49hear it, because it's kind of vague.
00:52People ask well, what is the DOM?
00:53Is it a language, is it part of JavaScript? What is it?
00:57Then you look it up on the web, and you find phrases like, "The Document Object
01:00Model is an application programming interface that defines logical structure of
01:03well-formed an XML and HTML documents," and it really doesn't help most people,
01:07but it's quite a simple idea at heart.
01:10So let's take the DOM piece by piece.
01:13Well, what do I mean by document?
01:15Well, if I am in Microsoft Word, that might mean one thing, but we're not.
01:20For us, the document simply means the page, not the site, the web page; the web
01:25page is the document.
01:27But this document can be represented in different ways.
01:30Well, it already is.
01:31You know this already.
01:32After all, which one of these is the web page?
01:36Well, both of them.
01:37One is the browser view, one is the source code.
01:40It's the same document; it can have a different representation.
01:43What we need to also understand is how JavaScript perceives the same document,
01:48same document, different representation.
01:51But if that's all we mean by document, then what's the object part of the
01:55Document Object Model?
01:56Well, when we talk about objects in programming languages, it's really easy to
02:00get wound up in deep semantic meaning, but we don't need to.
02:03We've already used objects in JavaScript.
02:06Dates are objects, arrays are objects.
02:08We've made our own objects.
02:10An object is just a thing, some thing, any thing that makes sense to treat as an
02:16individual piece, even if it contains other things.
02:19For us, it really means the elements, the components, the individual pieces of this document.
02:24If I talk to a user, I can say, "Look at the headline, look at the bullet point
02:28list, look at the whole page, even look at the third letter in the second word,"
02:32and they understand what I mean.
02:34If I talk to you as a web developer, I can say, "Now, look at the h1 tag, look at
02:40the unordered list part, look at the whole document."
02:43All of these things are objects and yes, sometimes they contain other objects. That's okay.
02:49You have no problem understanding the unordered list piece contains individual
02:54list item pieces, and in the same way, what we'll do is we'll have a JavaScript
02:58term for every piece, for every object at whatever level that makes sense, from
03:03the entire document to the smallest piece, and that leads us to the idea of the
03:09model of Document Object Model.
03:11Now, what they mean here is model as in a business model or data model.
03:15You've seen flowcharts or database diagrams, the idea of taking something
03:18complex and making it abstract, making it simple.
03:21But with a web page, we should be able to take any HTML and represent it as a
03:27tree structure. With the simplest of HTML here, it contains a head and a body.
03:33The head itself contains the title element, the body contains an h1 for a
03:38heading, a p for a paragraph, and an unordered list.
03:41The unordered list contains three list items.
03:44We're able with this diagram to represent the structure, the tree structure
03:49of this HTML document.
03:51We could even decide on words for these.
03:53If we were drawing this up on a whiteboard, we could call each of these pieces nodes.
03:58We'll pick a p or a body or h1 and call them all nodes.
04:01We could even develop terms to describe relationships, like picking a node and
04:05asking, what's its parent?
04:07Does it have any child nodes?
04:09And really. here what the model means is, what do we call these things, and how
04:13do we describe the relationships between them?
04:16Because it's not going to do me any good if I make up my own names for these objects
04:19that conflict with your names for these objects,
04:22if I call a piece a node and you call it a doohickey.
04:25So the model is simply a set of terms that we can agree on, a set of
04:30standards that we can use.
04:33So what we end up with is an agreed-upon set of terms that describe exactly how
04:38to interact with the pieces of a web page.
04:40That's a long phrase, so we call it the Document Object Model.
04:46It's not a language. It's an idea.
04:49It's a convention. But JavaScript agrees on this DOM, so it's available in JavaScript.
04:55It's an agreed-upon terminology that will let us describe and interact with any
04:59web page. Not one specific one, any one.
05:03When I know the basic concepts of the DOM, I can write JavaScript that
05:07navigates around any page.
05:09I can say I want to get the text of the title.
05:11I want to get the second paragraph element.
05:14I want to get the third link in the menu and change how it's displaying, in
05:18this case hide it, or change the background color of all paragraphs, or get all
05:22the list item elements, or find an image and start to move it, change a link from
05:27its default behavior to actually performing a JavaScript function, or even
05:31creating new unordered lists, or creating paragraphs, or creating menus and
05:35inserting them into the page on the fly, and a lot more besides.
05:41That's why we need to know the DOM.
05:43It is the way to reach into the page from our script and the way our page can
05:47reach into our script.
Collapse this transcript
Working with nodes and elements
00:00So we might think about our web page content one way, but the DOM thinks about
00:05it in terms of nodes.
00:07Every web page we have, every document is made of nodes.
00:11However, it goes a little deeper than just this basic example I am showing here
00:16of one node per tag, because as we know, our HTML does have tags.
00:21Sure, it has got the body tag, it has got p tag, header tags, and so on, but we
00:26also have blocks of text.
00:28We have attributes, sometimes one attribute, sometimes several attributes
00:33as part of an element.
00:35We can have comments and so on, and these are all regarded as different kinds of
00:40nodes in the DOM, and the reason for this is so we can get to them directly too.
00:45If I want to, I can ask, what is the text for the second paragraph?
00:49What's the source attribute of an image tag?
00:52So really, our diagram is a little bigger.
00:55If I had to display every single node here, I'd end up with quite a lot, because
01:00we have nodes that represent elements, attributes, texts, comments, and so on.
01:06And officially, if you look at the DOM documentation, there are actually 12
01:11node types in the DOM.
01:13But really, we're only interested in three of them:
01:17elements, attributes, and text.
01:20And here's an example.
01:21Let's say we have just a simple snippet of HTML here, an unordered list.
01:27It has got an id of optionList.
01:29It has got a three list items inside it.
01:31Well, the whole unordered list element from the top to the bottom is
01:36considered one node, an element node, but inside that it has another node that
01:42represents the attribute of id = "optionList", so it's a different kind of
01:46node, an attribute node.
01:48But as we start to look deeper inside it, we realize that we've got three list
01:53item nodes. Those are also element nodes.
01:56And not only that, because the text in any element is actually considered a
02:01separate node, each of these li elements has a text node attached to it to
02:07describe the text inside them.
02:09So as far as the DOM is concerned, we can drill into any very specific piece,
02:15even of this simplest little piece of HTML.
02:18Now, the idea that the text node is actually separate from the element might
02:23sound nitpicking, but it leads to quite a common mistake, that when you have
02:26element nodes such as paragraphs, or list items, or H1 tags, they do not
02:33directly contain that text.
02:35Officially speaking, according to the DOM, you have this text node that
02:39contains the text of a paragraph, or a text node that contains the text of a list
02:44item or of a heading.
02:46But having said that, we're typically interested in grabbing the element nodes first.
02:51That's the way most web developers think about an HTML page.
02:56It's made of elements, the tags that we have, our paragraphs, our anchor tags,
03:01our unordered lists, our headings.
03:03And the great thing is, once we have got any of those nodes, it's easy to work
03:07our way up and down the tree to get to any text node that might be below it.
03:10And luckily, it's not hard to do.
03:12So 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 Model
Accessing DOM elements
00:00So how do we write JavaScript to grab hold of one of these nodes?
00:04And well, it really depends.
00:06The main question you have to ask is, is it unique?
00:10The thing that you're after, is it unique in the document, and that means does it have an ID?
00:16If I'm after, say, an unordered list, I need to ask the question, does it
00:20have an ID in the HTML?
00:22You know that you can add the ID and class attributes to any of your HTML
00:27elements, but that a class can be added to multiple elements, but an ID should
00:32only be applied to one. It should be unique.
00:35And if the element that you're after has that unique ID, you can grab it in
00:39JavaScript by using possibly the most important method of the document
00:43object, which is this one,
00:46document.getElementById, and you pass in the ID of that HTML element.
00:54Now notice the uppercase and lowercase mixture here.
00:56It is, of course, case sensitive.
00:59So document is lowercase, then a dot, then getElementById.
01:03get is lowercased. Every subsequent word begins with uppercase.
01:07Element, By, and Id, but Id is not uppercase D, which often messes people up there.
01:13So what does this do? Well, we're going to call it, but not just like this.
01:17What we're going to do is create a variable and set it to the result of calling that.
01:24So if I want to grab hold of this unordered list that has an id of abc, I'm
01:29going to create a new variable called myElement and set it equal to
01:33document.getElementByID and pass in abc, the ID of the element.
01:38And what we're doing here is we're creating a variable that is really a handle
01:44to that place in the DOM.
01:46We can then use that variable, in this case I've called it myElement, to read
01:50properties of the element.
01:52You can call methods of the element.
01:53You can even change that element.
01:55Now it's important to understand that when I do this getElementById, I'm not
02:00just making this detached copy of this single piece.
02:03Now I have a handle right into this document.
02:06I can use it to go down to the child nodes.
02:10I can use it to go up to the parent node.
02:12It's not the detached copy of the one element;
02:15it's more like a pathway into this particular place in the DOM.
02:18Well, what if I don't have an ID on the element that I'm after, or what if I want
02:24more than one element?
02:25Well, then we have the getElementById's close relative, document.getElementsByTagName.
02:32Now notice, not getElement, but getElements, plural.
02:36What this is going to do is go through our document and give us back any of the
02:42element nodes that are anchor elements, a tags in your HTML.
02:46Well, how does that work?
02:48So let's say we go back to the same ID of the simplified DOM here.
02:52I'm going to create a new variable called myListItems and set it equal to
02:56document.getElementsByTagName, passing in li, which means, find me all the nodes
03:03that are list item elements and return those.
03:05Well, how does it store that in one variable? It makes an array.
03:10So it makes an array called myListItems,
03:13it finds all the list items in the entire document, and then in each position of
03:18the array, in this case, there's three positions to it,
03:21we'll have a handle to that particular place in the DOM.
03:24So we could just use the square qrackets and say myListItems(0) or myListItems(1)
03:30or myListItems(2).
03:30Now if you call the same method, getElementsByTagName and pass in a tag name
03:36that doesn't exist, so in my simplified model here I don't actually have any a href elements,
03:42what will happen is it will still return array, but the array will be empty.
03:47It won't even have a length of 1.
03:49It will have a length of 0.
03:50There's nothing there.
03:53So in this folder that I'm looking at here, I have a web page and some attached
03:57CSS and image just to give us something a bit more interesting to look at and to
04:02have a bit of content to work with.
04:04If I were to look at the page source of this, there's nothing
04:09particularly remarkable.
04:10It's standard HTML, although down towards the bottom, I do have a link to a file
04:15called script.js just before the closing body tag.
04:18And right now there is nothing in script.js.
04:24I'm going to open that up in Aptana, though I could open up in any editor.
04:34And just to have something else to look at, I'm going to flip over and just open
04:37up this HTML file in the same editor.
04:40I'm not intending to change the HTML here;
04:42I just want to be able to flip back and forth to it.
04:51So I can see by scanning my HTML that I actually have quite a lot of elements
04:55that have an ID to them.
04:58And the main reason this has been done is so they can be styled with CSS, but it is
05:03very handy for us as JavaScript programmers as well.
05:06I can see, for example, I have an anchor tag here with an ID of mainTitle.
05:12I'm going to write some code to grab hold of that.
05:14So let's create a new variable.
05:16I'll call it mainTitle.
05:28Again, we must take care to make sure that the casing that we're using to grab
05:32it is exactly the same as it is in the HTML itself.
05:36The variable I didn't have to call the same name.
05:39I can call that whatever I want.
05:40And the question is, now what?
05:42Well, I have this variable which represents the object, the element object, and
05:48like all objects, like dates, like arrays, like even strings,
05:51we have things that we can ask for them.
05:53So I'm going to write out a few console messages.
06:04And with console.log we can put a string, then a comma, and then some
06:07interesting information.
06:08So I'm going to say the message "This is an element of type" and I'm typing in my
06:16variable name, .nodeType.
06:18If you have an editor that pops up some of the auto-completion stuff, then
06:22great; otherwise, just type it in anyway.
06:24nodeType will be a property we can access as soon as I have something back
06:30from getElementById.
06:33If you recall, I said there were three kinds of nodes we were interested in:
06:37elements, attributes, and text.
06:40Internally, they should have the nodeTypes 1, 2, and 3, so this should write us back out 1.
06:47I'll do another one here, console.log. Writing out another property called
07:04innerHTML, and as always, paying attention to the case sensitivity of this.
07:19And the last message I'm going to write out is a message that will tell me how
07:22many child nodes I have, because when we grab hold of this element, we don't just
07:28have the element by itself;
07:29we'll also be bringing along references to any child nodes it has, or if I want
07:34to look up the way, any parent nodes as well.
07:36So every node has a childNodes property that might be empty, but I don't think it is here.
07:41It's actually an array, so it itself will have a length property.
07:45I'm just going to hit Command+S or Ctrl+S to save this, flip back over into
07:51Firefox where I actually do still have this running, and refresh the page.
07:55Now I'm doing console messages, so I need to have Firebug opened to actually see the console.
08:05Refresh that page, and we get "This is an element of type:
08:091." The Inner HTML is apparently Welcome to Explore California!
08:16and this particular node has one child node.
08:19So we're programmatically reaching into the HTML here, grabbing this content,
08:25and finding information about it.
08:26This is the innerHTML path that I was actually pulling out.
08:29I'm going to jump back in and do a little bit more code here.
08:34Now, let's use the document.getElementsByTagName.
08:37What I'm going to do here is create a new variable on Line 7 called myLinks,
08:41this will be an array, and tell this to fill it with as many anchor tags as I have.
08:46Then I'm going to write out a log message that just says myLinks.length.
08:51I'm just going to save that; for me Command+S or Ctrl+S, depending on
08:55what platform you're on.
08:56Back over into Firefox, refresh the page, and then apparently we have 19 links,
09:0319 anchor tags on this page, and we're getting all those elements by tag name.
09:08Yes, I'm not doing much with them yet, but you can see how we can start to drill
09:12down into the properties and the information about that data.
09:17So documents.getElementById and getElementsByTagName. Very, very powerful, hugely useful,
09:24probably one of the most often used things in all of JavaScript.
09:28And they're actually a little bit more powerful than this because even though most
09:32people think of this method as document.getElementById, it's more flexible than that.
09:38As soon as I have, say, an element node, I can use the same method at any level
09:44in the DOM, not just the top-level document.
09:47What does that mean?
09:48Let's say, for example, I have a slightly more complex DOM here and I run a line
09:56of code here that says getElementsByTagName.
09:58So it's document.getElementsByTagName("li").
10:02Give me all the list items back.
10:04If I can just run this, what I'll do is I'll grab all the list items from every
10:09level of the document.
10:10But let's say that's not what I was after.
10:13What I can do is kind of a two-stage thing here.
10:16First, I would use document.getElementById to grab that unordered list with an
10:23ID of abc, and that gives me a new variable called myFirstList.
10:27Then I'm going to call getElementsByTagName again, but instead of using the
10:32document to call it, I'm going to say myFirstList.getElementsByTagName.
10:38And what that means is it'll start at the unordered list position and look
10:43downwards and only give me back those list items.
10:46So I'm using another element, and you'll find this all the way up and down the
10:52DOM, that you're able to reuse the same method.
10:55Once you start to get to grips with the properties that are available and the
10:58methods that are available, you can pretty much get anywhere you want.
Collapse this transcript
Changing DOM elements
00:00Using JavaScript to read information about the nodes on our page is all very
00:04well, but we really want to be able to change it.
00:07Step one for doing this is always going to be get the element.
00:11You need that variable to be a handle on the element.
00:15Sure, we know that we've got elements, and we also have attributes and text
00:19nodes, but it's the element that comes first.
00:22Attribute nodes and text nodes belong to elements.
00:25If you're writing HTML, you don't write an attribute by itself.
00:29It's the attribute of an element.
00:31So that's what comes first.
00:32Step two is okay, then we can change it.
00:36The question is, what do you want to change about it?
00:38If you were manually editing this code in a text editor, what would you want to do?
00:43Do you want to pick an attribute and change it or add a new attribute?
00:47Do you want to change a link inside a heading?
00:50Do you want to add a whole bunch of new elements inside a div or inside a list?
00:55Well, we can do all of that, but let's talk about changing existing elements,
00:59rather than creating new ones.
01:01We'll get to that in a minute.
01:02One of the simplest changes we could make is to change an attribute of an element.
01:07Now once we've got that element, JavaScript actually has two methods we can use
01:11to directly work with its attributes:
01:14there's getAttribute and setAttribute.
01:17getAttribute is very simple.
01:18We just need to say what attribute.
01:21You pass this as a string in double quotes.
01:24It's the name of the attribute: align, title, class, source.
01:30setAttribute very similar, but we need a bit more information.
01:34We pass in a value.
01:36So we call the setAttribute method.
01:38We pass it the name in quotes.
01:39We pass it the value in quotes, always as a string.
01:42If the attribute doesn't currently exist, it will be created.
01:46Let's take a look at this.
01:48So I have a simple HTML page that I have here.
01:51There's nothing remarkable about it.
01:53It's just to have something to work with.
01:54You could work with a test page yourself.
01:57I have that open in my editor here, and down at the bottom, I have a link to my
02:02script.js file, which is in the same folder, which is actually over here.
02:08It has a few lines, but they're all commented out, just so you don't have to
02:11watch me type code all the time.
02:12So what I'm going to do is I want to grab hold of a section of this page and change it.
02:18The thing I'm going to grab is actually this div here on Line 22.
02:22It's got an ID of mainContent.
02:25It doesn't currently have any attributes set, but we can change that.
02:30So over in my JavaScript I am just going to uncomment Line 1 here.
02:33It's just a document.getElementByID of mainContent storing it in a
02:38variable called mainContent.
02:39Then I can use that variable, and just call setAttribute.
02:44The attribute is align, and the value is right.
02:47So I'll just save that JavaScript file, flick over into Firefox, and this is the
02:53area that I should be affecting.
02:55That's what that div is containing.
02:57So if I refresh this page, yes indeed, we've got align right now.
03:01So it's a very easy task to just change the attributes of an element that
03:06you have a handle to.
03:07Well, what if we want to get a little bit deeper than that?
03:10What if I want to change the contents of an element?
03:14Say I've got an h1 that I want to change or a paragraph that I want to change.
03:18Well, you have a couple of options here.
03:21The simplest option is a method called innerHTML, and that's inner in lowercase,
03:26and HTML in uppercase.
03:28You can use that on any element you have.
03:30It allows you to either read or change the entire contents of that element.
03:34So let's say here I've got an anchor tag with an ID of mainTitle.
03:41Right now, it contains the words "Welcome to Explore California!"
03:44I am going to jump over in my JavaScript, and uncomment a little line
03:48there where I am creating mainTitle and just using document.getElementByID of mainTitle.
03:54I'm now going to uncomment just a console.log message and ask for mainTitle's
03:58innerHTML property, save that, jump back over, and I'll refresh this page.
04:04You need to have Firebug open to see that.
04:11The console.log message is writing out Welcome to Explore California!
04:16So in this case, innerHTML of this anchor tag is giving us the text inside it.
04:21When you have a very simple tag, innerHTML can be a good way to work with it.
04:27A simple h1 is fine, as is an a tag, as is even there's a paragraph.
04:32Grabbing, for example, a div might give you a little more.
04:36Let's say we get a div that contains quite a few things, like this div ID of sidebar.
04:42If I do exactly the same kind of thing here, let's just change that and call it
04:46a var sidebar, and log out its innerHTML,
04:55jump back over to Firefox, and refresh the page,
04:57well, you see what we're getting here is the entire contents of that div and all
05:03its divs inside it and all its h2s.
05:05This certainly wouldn't be anywhere near as easy to start to manipulate as it
05:10would be if I just wanted to change the title or the words of a paragraph, or an h1.
05:15So if I want a little more finesse, I'm not going to use innerHTML.
05:20If it's an element that contains other elements, I might have a bit
05:23more thinking to do.
05:25The best way to explain how we actually start to drill down into the interior of the
05:29page probably comes from learning how to create elements.
05:33While you could use innerHTML and manually type all the HTML yourself in your
05:37JavaScript, that's not the best way to do it, as we'll see in a moment.
Collapse this transcript
Creating DOM elements
00:00While you could use the innerHTML method to just write out a bunch of HTML and
00:05dump it into a position in your document, it's not a clean way to do it, and it's
00:09easy to make a mistake.
00:10The best way is to start manually creating and inserting individual DOM element
00:16nodes into your document, and this is a very powerful technique to learn.
00:19It lets you change your page on the fly and to do it, there's always two steps.
00:24One, you create the element.
00:26You say I want to create a paragraph or a heading or a list item or an anchor tag.
00:32And step two is you then add that newly created element to the right place in
00:37the DOM, the right place in the document.
00:40So here's an example.
00:41If I imagine I've got a very simple HTML page representing here as a set of DOM
00:46nodes, I can see that my body consists of three things:
00:50an h1 heading, a paragraph, and an unordered list with an id of abc.
00:56That unordered list has three list items underneath it.
01:00And I can imagine I've already used getElementById to create a variable called
01:05myElement that points to that unordered list.
01:08That will be important in a second.
01:10So if I want to add a new list item to this point in the DOM, a new list item to
01:16the unordered list, what I have to do is first, step one,
01:19create the element.
01:20And instead of using document.getElementById, we use document.createElement and
01:27I pass in a string that says what kind of element.
01:30In this case, it's an li.
01:32If I wanted a paragraph, it would be a p;
01:34if I wanted an anchor tag, it would be an a; and so on.
01:36Now that creates it, but it creates it kind of out there in space.
01:41The element exists, but it's not part of the DOM itself.
01:44So the next thing that I need to do, step two, is call the appendChild method of myElement.
01:52So I'm actually saying for the unordered list, append the child this new
01:57element, the list item.
01:59JavaScript will take it.
02:00It will make it part of the DOM and understand its place in the document itself.
02:04Now right now, this list item would be a little bit basic because we haven't set it.
02:09We haven't given it any text, and that's usually what we expect with a list item.
02:13Well, I could, if I wanted, use innerHTML and just actually set the text of the list item.
02:20And that would work, but there is a preferable way to do it as well, or a more
02:24exact way, which is that after we've created the element itself, we then
02:30create a text node.
02:31Remember that the element and the text they contain are actually different.
02:35So if I've got that variable myNewElement that points to that list item, what
02:40I'm then going to do is use the createTextNode method, which creates this text
02:45node. Very similar to creating an element,
02:47it's out there in space, not attached to anything.
02:50And once again, we use appendChild, except this time we're adding it to the NewElement.
02:56This would be the most exact, the most specific way to start creating these DOM elements.
03:03So let's do a demo.
03:04So in my browser, I have a page that I already created.
03:08It's just a fairly regular web page.
03:10But down here a little bit further, I've got this area that I want to generate
03:14some content in, and I'm actually going to do that using JavaScript.
03:19This blank area here, if I look at my HTML, is actually represented by a div
03:25with an id of trivia.
03:28So this is the place that I want to create new DOM elements and add them right here.
03:34So the way to do it, if I come over to my script.js file, I've got some code
03:37that already exists.
03:38I'm just going to uncomment it.
03:42And I'm actually going to do two things here:
03:43I'm going to create an h1 element, and then I'm going to create a p, or paragraph, element.
03:49So lines 2 and 3 we actually create new variables creating those elements, but
03:53they're just existing out there in space.
03:55They actually aren't part of the page yet.
03:57Well, not only that, they don't have any content.
04:01So if I want to do the slightly easier way but not as exact as possible, we
04:06could call the innerHTML on both of these new variables.
04:10So newHeading, which I just created, set its innerHTML to "Did You Know?"
04:15And the newParagraph, which I just created, set its innerHTML to "California
04:20produces over 17 million gallons of wine each year."
04:23So we have our elements, we have some text added to them, but they're still
04:28not part of the page.
04:29And in fact, right down here on Line 17 and 18 I'm just going to uncomment
04:33these lines because this is how we add them to the page.
04:38If you remember, the div that I wanted to add them to is called trivia.
04:42So we call document.getElementById ("trivia").appendChild(newHeading), we're
04:48adding the h1, and then we call the whole thing again, and then we say we'll now
04:53append another child, which is the paragraph.
04:56So if I save this and I just open that up in the browser again, what we'll
05:01find is that that part of the page that was blank now has this content that's
05:06been dynamically added.
05:07And because it's using the same CSS rules as the rest of the page, I have a
05:11formatted headline with the underline and I have the correct font showing up.
05:15But let's just talk about the more exact way of adding text.
05:20We can use innerHTML, but the alternative way is going to be below here.
05:25It's going to require two more lines of code, but it is a bit more exact.
05:29And we do it similar to creating the elements themselves.
05:32We actually create new text nodes.
05:35So on Line 10, I'm creating a variable called h1Text and calling
05:38document.createTextNode and giving it a little bit of text to initialize itself,
05:43and then the same thing on Line 11 for the paragraph.
05:47But because you create text nodes just like elements that are just existing
05:51disconnected out in space, what I'm then doing is on Line 13 and 14 I'm
05:58associating those new text nodes with the new h1 and the new paragraph that I
06:03created on Line 2 and 3.
06:06And I'm leaving line 17 and 18 exactly as they are because we still need to add the
06:12new heading and new paragraph to our DOM.
06:15Save that, jump back over into the browser, and if I refresh this, we should see
06:21absolutely no changes at all.
06:24Again, you can make your own decisions about which method to use.
06:27Creating text nodes separately does mean typically writing a little bit more
06:31code, but it is a more exact and more specific way to do it.
06:35So while the process is always going to be a step one, create the element,
06:38step two, add it to the DOM,
06:40there is an alternative to appendChild, although that is the most common one.
06:45Instead of just pointing to the parent element and saying appendChild, we also
06:49have the choice of insertBefore.
06:51So if you want a bit more flexibility about where our new element is inserted
06:56into the DOM, we can use this one as well.
06:58Let me show an example here.
06:59So taking the same idea of that DOM tree that we had before, appendChild will
07:06always add that new list item right at the end.
07:10It will always add it, as in this case, the fourth list item.
07:13But what if I didn't want that?
07:14Well, step one is still the same:
07:17create the element.
07:18We're creating it there out in space.
07:20Now the second step here is I need to grab hold of a variable that points to, in
07:25this case, let's say the second list item, and I'm going to do this by calling
07:30getElementsByTagName, because that second list item doesn't have an ID.
07:35So I'm first calling myElement.getElementsByTagName, saying I want to find all
07:41the list under the unordered list.
07:44And then I'm using the square brackets and saying number one, which if you
07:47remember, we're going to use zero-based arrays, so the first one would be at
07:51position 0, the second one at position 1, the third one at position 2.
07:56So I now have a variable, secondItem, that points to the second list item.
08:00And what I can do is use the other way of adding to the DOM.
08:05Instead of appendChild, I call myElement.insertBefore and the two pieces of
08:11information I give it is what's the new element and what's the element you
08:15want to insert it before, in this case, secondItem, at which point it will
08:19reshuffle that arrangement and insert my new list item into that very specific point in the DOM.
08:26So most of the time, you'll be using appendChild, but insertBefore can come
08:29in very handy as well.
Collapse this transcript
6. Working with Events and Event Listeners
Introduction to JavaScript event handling
00:00So we're starting to write some deeper code, but it's still happening as soon as
00:04the browser gets to it.
00:05And that's not a very interactive situation.
00:08We're not reacting to anything the user is doing yet.
00:11We can fix that by working with events.
00:14Maybe I've got some JavaScript that I only want to run when a link is clicked on
00:17the page. Or if the user tries to submit a form, I want to make sure that
00:21they've filled out the form first.
00:24And I want to make sure that not only has the page loaded, but also all of the
00:28assets it's linking to, including images and style sheets and so on.
00:31And we can do all of these things and a lot more with events.
00:35Now here's the thing with events.
00:37It's common for someone new to JavaScript or new to programming to get a little
00:41puzzled about your role here. You're thinking, "Am I supposed to write the event?
00:45How do you describe an event?"
00:47Well, you don't, because here's the deal.
00:50The events are already happening.
00:52They've been happening all along.
00:55When the page is loaded, that's an event;
00:57when the user clicks a button, that's another event;
00:59when they move their mouse, that's a whole bunch of events;
01:02when they scroll the screen, that's an event;
01:04when they click a form field, that's an event; as they type, every key press is another event.
01:09Events are going on all the time.
01:12You have to decide which ones you care about.
01:16See, these events are built into JavaScript.
01:18They're part of JavaScript, and there are special words to describe them.
01:22You'll see them typically written all lowercase, and they begin with the word on,
01:26so onload, onclick, onmouseover, onblur, onfocus, and we'll see several of these
01:32in the next couple of movies.
01:34But you don't write the event itself.
01:36You write what's called the event handler or the event listener, whatever term you prefer.
01:42You write your function and you volunteer to handle or to listen out for one or
01:47more events, so that you can respond when they happen.
01:50And I'm going to talk about and cover three ways you can react to an event in JavaScript.
01:55One is the simplest and the ugliest way.
01:59You can just write JavaScript code directly in your HTML, so if you have a
02:03button tag in your HTML, you can use that word onclick--
02:07again, this is the event--onclick = and in this case I'm just directly typing in
02:12JavaScript, the alert('Hello, world') here.
02:15I'm not a fan of this method, for multiple reasons.
02:18It's going back to having script mixed in with our HTML, which I'd like to avoid
02:22as much as I like to avoid CSS mixed in with our HTML.
02:26While you can include multiple statements here separated by semicolons, really,
02:31how much do you want to write like this?
02:33And if we did this a lot, we wouldn't be reusing code like we can with
02:37an external file, and there's no way to make this friendly if JavaScript is disabled.
02:42But you will see it from time to time.
02:44The second way is to use the name of the element, then a dot, then the name of the event.
02:49So window.onload means the onload event of the window object;
02:54nameField.onblur means the onblur event of the nameField object; or quite
02:59classically, just myelement.onclick.
03:02When they click a DOM element, we want to do something, so we use the equal sign
03:06and then this following format:
03:08the word function(), and then the opening and closing curly braces,
03:14and then you put your event handler code inside here, whatever you want to
03:18execute when they click that element, whether that's one line or a hundred.
03:24And what we're doing here is what's called an anonymous function.
03:27This is very, very common in JavaScript, and you'll see it all over the place.
03:32It might look a little weird because usually we use the word function and we
03:35give our function a name, but we're not doing that here. And that's okay.
03:39Think about the reason for a function.
03:42We usually use a function to wrap up a bunch of code and give it a name so
03:45we can call it later.
03:47Well, here, we're still using the word function to wrap up a bunch of code--
03:50whatever is in between the opening and closing curly braces--but we don't have
03:54to give it a name because we're saying exactly when this gets executed, which is
03:59when they click myelement.
04:01So when this event happens, we want to run this function, whatever is in
04:05this block of code,
04:06so naming it would be a waste of time.
04:08Now one important thing here, bear in mind, if you write this code, the first
04:14time JavaScript reads it, it won't actually do anything with the function.
04:19What you're actually saying is later on when the user clicks this element,
04:23we execute this code.
04:24I'm just telling you about it right now.
04:26And because of that, there's a little addition to this that often messes people
04:31up when they first see it, which is we're ending this all with the semicolon.
04:37And it's very common for beginners to JavaScript to look at this and go,
04:40"I don't quite understand.
04:42I didn't think we used semicolons around functions."
04:45And people get very puzzled because they think, "When do I need a semicolon. Do I
04:48put it at the end of a function or don't I put it at the end of a function?"
04:51Well, the thing about it is this:
04:53it's nothing to do with the function.
04:55We're not putting the semicolon there because this is a function;
04:59we're putting the semicolon there because the whole thing is a statement.
05:04We're saying myelement.onclick = this function.
05:08That's why the semicolon goes at the end of the block here.
05:12The same way I put a semicolon at the end of var a = 5,
05:16I put it at the end of myelement.onclick = function().
05:19In most cases, it would work if you forgot the semicolon, but you will see this format a lot.
05:26And then there's the third method of deciding to handle or register for an event.
05:31This has one huge benefit and one huge drawback.
05:37It's using a method called addEventListener, which you can either call directly
05:41on the document object or on any element that you have.
05:45And you give it three pieces of information:
05:48the event--and here you actually write it without the word on, so click rather
05:52than onclick, mouseover rather than onmouseover--
05:56then a comma, then the function you want to run, and then the term false.
06:00We're actually interested in the first two arguments here.
06:04What event are we listening for and what function gets called when it happens?
06:08This third false argument is an option for some super-advanced event handling
06:12that's very unusual to need.
06:13Now the big benefit is using this way you can actually add a listener
06:19to multiple events. You can add one event and have multiple listeners.
06:23You have a lot of flexibility to dynamically add and use its mirror image to
06:28remove event listeners as your script is running.
06:31If that's the big benefit, here's the big problem.
06:34This is one of the very few areas left where there is still a difference
06:39between the browsers.
06:41Because Internet Explorer, prior to IE 9, does not have the addEventListener
06:46function. It has its equivalent which is the attachEvent method, which takes two
06:53parameters. Same idea;
06:54it's the event name itself and then the function.
06:57It's the same concept, but it's a different name.
07:00And that's a small difference that makes a big difference because to use this
07:05we now need to write code to detect whether or not these functions exist.
07:10And if I wanted to be agnostic about the browser, what I'd probably typically do
07:15is write my own little helper method. I'd write my own function called say
07:19addCrossBrowserEventListener, and I could pass it information.
07:24And it would do a little bit of scanning to see, does the EventListener function exist?
07:29If it does, we'll use the addEventListener function;
07:31if it doesn't, we'll use the attachEvent one.
07:34Now here's the thing.
07:35I have written a lot of cross-browser detection code in my time, but these
07:40days I do my best to avoid ever handwriting functions that deal with
07:44cross-browser issues.
07:46If I need the benefits of addEventListener and attachEvent, I will not write my
07:51own code to handle the difference.
07:52I'll use one of the free third-party JavaScript libraries like jQuery.
07:57A big part of what they do is provide excellent cross-browser functions for
08:02situations like this.
08:03We'll talk about these libraries a little later.
08:06Because of this reason, in this course I'm going to be using the simpler, more
08:10straightforward, but cross-browser compatible methods of creating event handlers.
Collapse this transcript
Working with onClick and onLoad events
00:00So now I'm going to write some code to respond to common events, and if there are
00:04two events in any programming language that are the most common, it's clicking
00:08on something and loading something.
00:10So I have a regular HTML page here with some images and CSS linking to a
00:16JavaScript file that's actually currently empty, and I have both of those just
00:20open in my editor here.
00:22So the simplest way that I could cause something to happen is like I have on
00:27Line 28 here where I just have the onclick = inline code in my HTML itself, and
00:35no particular surprise on what this is going to do. If I click that button, I'll
00:39run that alert message.
00:41But we are not going to do any more code like this.
00:43We are going to do it properly.
00:45So I am going to jump across into my script.js, which is already being linked
00:49to, but there's no script in it yet.
00:51Now it's easy to think that we need a button or a link to click on.
00:55We can support the idea of clicking on anything in our document.
00:59Click is a very generic event. And we mentioned that we need to
01:02write element.event,
01:04so what's an element?
01:05Well, one of the top-level ones I have here is document.
01:09The document is an element itself.
01:11document., and event name, I'll say onclick =, and this is where we then write
01:18what's called the anonymous function.
01:20This isn't the only way of doing it here, but this is the most common way.
01:24So the word function, opening and closing parentheses, and opening and closing
01:28curly braces that contain whatever code I want to execute.
01:32In this case, I am going to do something simple,
01:34alert ("You clicked somewhere in the document").
01:43So I jump over to the browser,
01:44I reload the page, and as soon as I clicked, I should get that alert message.
01:49The only thing I have to be careful with would be clicking on perhaps one of
01:52these links, which actually won't go anywhere right now and get a missing page.
01:56But you can see I don't have to click explicitly on a button; it can react to it anywhere.
02:03Now it's probably not all that useful to make the entire document respond to clicking.
02:08So what we could do instead, I am going to jump over and do a slightly
02:14different one here.
02:15First, I'm going to create a variable.
02:27First, I am going to create a variable and just grab hold of an image which has
02:32the ID of main image, because if I want to respond to an event, I don't have to
02:37respond at the document level.
02:38I don't have to say document.onclick.
02:40I can use any element.onclick.
02:43So now I got that image, I could say myImage.onclick = another anonymous
02:51function, and we'll pop up in the message, You clicked the image.
03:02Save that, jump back over into the browser, and refresh this page.
03:08Now if I click the image, I should get the message, "You've clicked the image,"
03:12though having said that, this is also considered a document click,
03:16so I'll get that other event as well.
03:19If I click somewhere off the image, I'll just get "You've clicked somewhere in
03:22the document," but it can also target the image, which again, has the document as well.
03:29So you can target this event handling at any level that you want to.
03:34You don't have to have a button or a link to click on.
03:38It can be any element on the page.
03:40Up to this point, what I've done is I've recommended always putting any links to
03:45external JavaScript files right here at the end before the closing body tag, and
03:49that is a good rule.
03:51However, it doesn't guarantee that your page and all its assets are loaded.
03:55If you're loading CSS files, images, et cetera, you might actually hit and run
04:00your JavaScript before everything has been fetched from the server.
04:03So it's very common to make sure everything is loaded before we start running
04:07any JavaScript at all.
04:08I am going to emulate this by just doing a little trick here.
04:11I am going to grab the script tag and just put it up here somewhere in the
04:16head of the document.
04:17So it's going to be loaded as soon as the browser sees Line 7, before it even
04:23gets onto the body here.
04:24I am going to jump over into script.js.
04:27I am just going to remove that document.onclick function, because I don't
04:32really need it here.
04:34I just want one responding.
04:36So still I have that code to say when you click the image pop up an alert box.
04:42I jump over to the browser.
04:43I am going to reload this page.
04:45Now if I click this image, I don't have anything, because the problem here is
04:54that the browser is trying to execute this JavaScript as soon as it gets to it.
04:59It's trying to grab this element called mainImage, but it's trying to run that
05:05around about here, before it passes the rest of the page.
05:08It doesn't have an element called mainImage.
05:10So it can't add itself to onclick.
05:13So how do we deal with this?
05:14Well, this is a very, very common issue, and the event we want to respond to is
05:20the onload event of the window object, not the clickevent of the myImage object
05:26or the mouseover event of the document, but window.onload.
05:31Now we haven't really touched on the window object very much.
05:34We've been staying focused on the document object.
05:37The window actually represents a full browser window.
05:41It is actually the top-level object in JavaScript. It contains the document object.
05:46And it's this that can tell us when everything is loaded.
05:49I use the same format, the.event format here, and I'll just do an
05:54anonymous function.
06:03So call any other functions, "prep anything we need to." In fact, a good idea
06:07here is that what I might do is create a new named function.
06:15Let's imagine that we had multiple event handlers that we were worried about.
06:20So I am going to grab my code and paste it in there, so that when this
06:30function is called, it will try and add an event handler to the image, but I
06:35am going to make sure that function doesn't get called until the document has completely loaded.
06:42Save that jump, back over into the browser, and now, even though the JavaScript
06:48is loading immediately, we should get our successful event handlers popping up
06:54here, because the browser is reading the code.
06:59It's understanding the function and then it's hitting this window.onload and
07:03realizing, okay, I'm only going to call Line 18 after the document has fully
07:08loaded, regardless of where the script was placed in the HTML.
07:12Now as we get more complex, one thing to watch out for is that you should only
07:17write this window.onload function once per page, and if you ever link to
07:22multiple JavaScript files and find out that you've got multiple files trying
07:27to do the same thing, it's only the last one that's going to win. But window.onload is a very common
07:32event and one you are going to react to a lot.
Collapse this transcript
Working with onBlur and onFocus events
00:00Here are two more events, very useful when working with forms.
00:04No doubt you've seen this one before.
00:05You're filling out a form on a web site and one or more of the fields actually
00:10has a value already pre-filled in, perhaps prompting you what to do.
00:15You can either click in there or tab into that location and that text will disappear.
00:20However, if I tab out of it again, the text comes back to prompt me that I need
00:24to put something in there.
00:26This is very easy to do using the onfocus and onblur events in JavaScript.
00:32Every one of our form elements here gets an onfocus event kicked off when we
00:37click into it, or when we hit the Tab key and tab into it, and when we leave it,
00:43that element gets the onblur event.
00:46So to create something like this behavior is very simple indeed.
00:50Let's take a look at the HTML, then the JavaScript.
00:54My HTML is nothing special.
00:57I have a form created and I have an input element here for the email, and it
01:02has got an ID of email.
01:05And simply, in the JavaScript, Line 2 grabs a hold of a reference to that email
01:11field, and then we add two event handlers to it.
01:16For my emailField.onfocus we'll execute this function, and for onblur we'll
01:21execute this function.
01:23So onfocus, meaning we click into it,
01:25what it's asking is if the value of that text field is your email, all in
01:30lowercase, then we're going to set it to blank and allow someone to type in a value here.
01:36Now, notice that what we're doing when we're trying to grab the contents of the
01:39textbox, it's the .value property, not .innerHTML, but .value, and that's the same
01:46for pretty much every form field.
01:48So the value is your email, we'll blank it out.
01:51However, when they leave and we kick off the onblur event, it's going to ask,
01:56well, did they leave leaving that value as blank, and if so, what we're going to
02:00do is change it right back to your email.
02:04So, very easy to do.
02:06if we leave that form field, the value changes to your email. If we click
02:10back in, it goes blank.
02:11If I type in a value, it will not overwrite it with your email, although that
02:17might not be what we want.
02:19I'm just checking that they typed something here.
02:22If I wanted to write a little bit of code to check it was a valid email format,
02:26I could use something called regular expressions, and that's available in
02:30JavaScript to do pattern matching.
02:32But regular expressions are another movie.
Collapse this transcript
Working with timers
00:00It's very common to want to trigger some JavaScript to run but to run later, to
00:05call a function after 60 seconds, or to call a function every 5 seconds, and we
00:10use timers for these.
00:11Slideshows would use timers, clocks would use timers, and there are lots
00:15more uses for them.
00:17While timers aren't officially events in JavaScript, they can feel a little bit
00:21like it, so we will talk about them here.
00:23Really, there are only two methods that we are interested in.
00:28I'm looking at a little bit of code here, but there is nothing to do with timers just yet.
00:31I have a function defined called simpleMessage.
00:35I'm going to add just a call to setTimeout.
00:38We can just call setTimeout directly the same way we could call alert or console.log.
00:44It's always available.
00:46All I need to give it is two things:
00:48the name of the function I want to call--in this case simpleMessage, comma--and the interval.
00:55Now, setTimeout is used in milliseconds,
00:58so if I wanted to say pop up five seconds later, I'll put in 5000.
01:03Finish that statement.
01:05We can ignore anything that's below it.
01:07Right now, it's not being used yet.
01:08I am going to save that, and I'm going to refresh the page that I am on that's
01:12actually using this.
01:14Open that up, and then hopefully in about 5 seconds, we get the alert box.
01:21Yes, I agree, not very exciting, but it proves the point.
01:25Now, when I use setTimeout, it just happens once.
01:28It hits that line of code and says, "I am going to do this once and that's it."
01:32We also have a different one called setInterval.
01:36setInterval takes exactly the same format, but it repeats it.
01:43In this case, setInterval will call the function called changeImage every five seconds.
01:49Now, what do I have going on here?
01:52Well, just to break it down, what I am doing is on line 10 I'm grabbing hold
01:57of an element of the page called mainImage, and if I look at the HTML here, all
02:05I have is that mainImage isn't a regular image tag in the main section of my document.
02:11So I am grabbing hold of that, so I can change the source of it.
02:16On line 12 and 13 I am creating an array, using the shorthand format within the
02:22square brackets, and all I'm putting in it is six paths to images, and these are
02:28just some images I have locally in the _images folder that I have here.
02:36I've gone through and manually entered these.
02:38Now what I am going to do is rotate around them.
02:41So I am creating my own little index here, which I will set at position 0, and
02:46then in my function called changeImage I'm going to reach into that image
02:51and set its source attribute to whatever the current contents of the array
02:57are at the current index.
03:00So the first time we call it it will say, "Well, my index is set to 0.
03:04I will grab the image that's called overlook. jpg, and just add that entry to the image tag."
03:10Then we add one to the imageIndex.
03:13We check to see if the index is larger than the length of the array; it isn't.
03:17So I am done with the function.
03:19But setInterval is still ticking, and in five more seconds
03:23it's going to call changeImage again.
03:25We then grab the second element, we change the attribute, we increment the
03:31index, and we just keep going.
03:34So if I save this, go back over to my page, and hopefully, after about five seconds
03:44we change to one image,
03:46we wait a few more seconds, it will change to the next one, and as we watch, it
03:49would keep going and just start to loop around.
03:53A very simple use, and all we're really doing here is the setInterval.
03:58But both setTimeout which is the single one and setInterval which is the
04:02repeating one have their mirror images,
04:05the ability to both clearTimeout and clearInterval. So just because we start
04:11something repeating, doesn't mean we always want to go on that way.
04:15The question is, how do we do it?
04:16Well, here's the interesting thing.
04:18When we call setInterval--I am just going to bring it up a little bit so I
04:22can see more to it--
04:24this function actually returns a value, and I'm going to store it.
04:28I didn't care before, but now I do.
04:30I'm going to create a new variable called intervalHandle. That's as good a name as any.
04:36It's just going to be a variable that connects me to a little bit of memory that
04:40says 'I understand what this interval is doing.'
04:43What I am then going to do is say, when somebody clicks on the image--so I'll
04:48use the myImage.onclick event = function(), just a small anonymous function--
04:55I'm going to call, instead of setInterval, I am going to call
04:58clearInterval, passing in that interval handle, the variable that was
05:06returned from calling setInterval.
05:09Now, you might think, "Well what does that do?"
05:10It allows me to create this ticking clock, this setInterval, and if I want to
05:17pass that value right into clearInterval then it knows which one to clear.
05:22The idea of this is I could have multiple intervals kicking off in my JavaScript.
05:27I don't want to clear all of them or none of them;
05:29I need to know one at a time.
05:31So I'll save that, jump back over, and open my page again, and we should
05:35have the ticking clock going on. The setInterval should be refreshing this
05:40image every five seconds.
05:44But if I click on it, single-click, I'm not asking for any feedback, but that
05:50setInterval should now be cleared. And as you notice, the picture is not
05:54ticking over anymore.
05:56That is simply timers in JavaScript.
05:59Working with timers in JavaScript really boils down to those four methods:
06:03setTimeout to perform a single action after a delay, setInterval to repeat it
06:10after that delay and just keep on repeating, and their evil twins
06:14clearTimeout and clearInterval.
Collapse this transcript
7. Debugging JavaScript
Common JavaScript errors
00:00We may be creating web pages, but this is programming, and no matter how good we
00:04get, we'll spend less time writing code and more time figuring out why the code
00:09we wrote doesn't work.
00:10JavaScript is a forgiving language, but there are still common problems to be aware of.
00:14Now when you look at a page and it doesn't do what you were hoping, know that
00:18many JavaScript problems have failed silently. There will be no error message.
00:22They just won't work,
00:23although we can get some error message from some of our code, and let's cover those first.
00:29Make sure to have your JavaScript debugger, like Firebug, open, as the default
00:33configuration of most web browsers won't alert you to any JavaScript issues.
00:37They just won't work.
00:39I'm going to refresh this page, and with Firebug open, it's giving me a
00:42problem here, and this is the situation, that first, and most importantly, we
00:47might have syntax errors.
00:49So I'm going to jump over to Aptana.
00:51I'll go to small JavaScript file that I'm using here with a few of the very
00:56common errors I want to show you.
00:58Most of it's commented out.
00:59I only have a few lines of active JavaScript here.
01:02First, and most importantly, you have syntax errors.
01:06Did you miss a closing brace, a closing bracket, or parentheses, or did you add an
01:10extra one, because these and many more will interfere with any of your
01:14JavaScript being understood.
01:16One of the things you'll often see programmers do is when they are typing, say,
01:19if statements, they will actually type the opening and closing parentheses and
01:23the opening and closing curly braces before they then go back and start filling
01:27the things out, just to make sure that they are not messing it up.
01:31Now if I have code and there is a problem with this code here, over in Firebug
01:35it's actually saying that I've got a missing colon after property id.
01:39Now that message itself might not be very helpful, but when you do see messages
01:45that don't appear to make sense, you just need to start looking at your code.
01:48Now, that's the message Firebug would give me. If you're using the Developer tools
01:52in any of the different browsers, they will often give you a different message.
01:55What I'm missing here is the closing parentheses after myFunction name.
02:00I am going to save that, go back in and refresh the page.
02:04Now I've got an unterminated string literal, and it is complaining about a particular line.
02:10If I even click the line, it would take me straight to that.
02:13What it appears to be there is another syntax error.
02:16I don't have the closing double quote.
02:18I'm going to go back and drop that one in, save that, back over into Firefox,
02:24refresh the page, and I actually get the normal log message, which was what I was hoping for.
02:29But even after your syntax is correct and it's understood by the browser,
02:34there are still millions of mistakes that can happen.
02:36Now let's go through some common ones here.
02:38So I'm going to just comment this code out, because we've solved that one, and
02:44talk about possibly one of the most common situations here.
02:48You create a function called, in this case, myFunction, and you call it, or so you think.
02:54If I save this code, I go back into the browser and refresh it saying,
02:58myfunction is not defined.
02:59This is one of the situations that will actually cause an error in any of the
03:04JavaScript debuggers.
03:06You're trying to call a function that doesn't exist, whether that is because of
03:10this situation just a typo.
03:12I've called it a lowercase f for function when I'm calling it, but I defined it
03:16with an uppercase F. Saving that, we refresh that page, and everything is working again.
03:22So calling a function that doesn't exist, a very common cause of JavaScript
03:27errors, and very common also, that you do a typo in some of the DOM methods,
03:33such as getElementByID.
03:36In this case, this wouldn't work.
03:38If I save this, refresh this, I'll get a slightly different message:
03:42document.getElementByID is not a function.
03:45And you might be sitting and thinking, "Of course, it is. I've used it a hundred times."
03:49But of course, case sensitivity here, the D at the end of getElementByID
03:54should be lowercase.
03:56It's giving you a slightly different message here, because this is considered a
04:00method of an object rather than a function.
04:03Again, depending on what browser you're using, you may even see
04:06different messages for that.
04:08The equivalent of that with your own code might be that you say create an
04:12array, such as I'm doing here on line 29, and I'm trying to call one of the
04:16object methods here called reverse, but I spelled it incorrectly, and we're
04:21going to get that equivalent there: myArray.revers is not a function--which is of course true.
04:26So comment goes back out and moving on.
04:28Now couple of situations we've talked about before.
04:32One is if you're creating a variable and calling document.getElementById, but
04:37there is any chance that actual part of the page hasn't loaded yet,
04:41you'll only have an undefined variable here.
04:43This won't actually cause an error.
04:46Your code just won't work the way you expect it to, and that happens more and
04:51more as you get better with your code.
04:53You're not going to get those very obvious errors about functions not existing;
04:57it's just not going to work.
04:59Classic situation, of course, being this one.
05:01On line 41, I create a variable, a = 10, line 42 var b = 20, and then I have an if statement=,
05:08if (a = b), or so I think.
05:10Now in this case, I think a should never be equal to b, but I'm doing the
05:15assignment instead of equality.
05:18So in my own mind I would never expect this message to come out, but of course
05:22this is exactly what's going to happen.
05:25Now notice there is no error message in Firebug, because technically the syntax is correct.
05:30But I'm getting this console.log, that "Something is wrong with the universe,"
05:34because we're doing assignment instead of equality.
05:37We're setting a = b here, not checking a = b.
05:42A mistake that all programmers in C-based languages will run into once in a while.
05:47We'll change that, swap back over and I should have the message, "This is what I expect!"
05:51which of course it is.
05:52Now again, moving on to a couple of things that would cause errors in other
05:56languages but don't officially cause errors in JavaScript, even though the
06:01behavior might not be what you want.
06:03Let's say this one, for example.
06:05I've defined a function called calculateSum.
06:08It takes three parameters--a, b and c-- and returns the value of those added together.
06:13Then a little later on I'm going to call it.
06:16I'm going to call calculateSum, passing in two parameters, and storing whatever
06:21comes back in my variable called result, and then writing out
06:24console.log(result).
06:26Save that, jump back over into the browser.
06:28Now, this is not an error.
06:31All that I'm doing is writing out the contents of that variable, which is
06:35technically not a number.
06:38But I'm not getting any problem in the status bar.
06:40It's just an unexpected result, not an error, and those are two very different things.
06:44And of course this is because I am allowed to call a function passing in less
06:50parameters than it was defined with. What's happening here is that c would be
06:55accepted as undefined.
06:57Then the code tries to add three together.
07:00If you are try and add an undefined variable together, that doesn't make sense,
07:03so the result is not a number.
07:05Now, there are of course a million ways your code can fail, but looking out for
07:10these basic situations will clear up a lot of those core issues.
Collapse this transcript
Using Firebug
00:00So we've been using Firefox with Firebug, although these days every modern web
00:05browser has the equivalent tools.
00:07Safari has their developer tools menu, as does Internet Explorer, as does Chrome,
00:12Opera has Dragonfly, and without exception, these days, they are all very, very
00:16good, but Firebug is certainly the best known.
00:20Now we've been mainly using it so far for the Console panel to view console
00:24messages and to type JavaScript, but it's much more useful than that.
00:28If you haven't used this already, you can use the HTML tab to actually scan and
00:33expand the HTML that you're using.
00:35If you notice that as I'm mousing over different sections here, it's actually
00:38highlighting in the top part of the page.
00:41And you can view the DOM, the actual Document Object Model of this page.
00:46I can see the document here, start to open that up, and drill down inside it.
00:51The DOM is very useful, but it can be a little intimidating at first because
00:54you'll realize there is a lot more going on with the DOM than just a few nodes.
00:59You quickly see that each node has many more properties than we could cover in
01:03this course, but you can view the properties of a particular node.
01:06I'm looking at document right now.
01:08I can see if it has any childNodes. Yes, it does.
01:10Here is HTML, drill down into that.
01:13Does it have childNodes? Yes, it does.
01:15It has the head section with a blank line between them, which is technically a TextNode.
01:20Open the body. Does it have childNodes? Well, I'd hope so.
01:24Yes, it's got div. It's got script.
01:25It's got TextNodes itself.
01:27And you can also scan to figure out if any of these have properties that you
01:31might be interested in.
01:32Now one good thing is if you're much happier with HTML, and most people are, at
01:36least to begin with, you could drill down into your HTML, say, into the footer
01:41and into a footermenu section, find a particular place, say, such as this h3, and then
01:47use the Context menu, right-click or Ctrl+Click depending on what operating
01:51system you have, and click Inspect in DOM tab and it would drill you down directly
01:56into the particular node that you're looking at here, which if I start browsing
02:01through, I can even see that this one has childNodes.
02:04It's got one childNode and at position zero, it's the TextNode with the contents
02:09Quick Nav inside it.
02:11Now one thing worth pointing out with this is if you are using JavaScript to
02:16change DOM content after your HTML has loaded, know that you won't see your
02:22changes if you're just used to the View Source feature of the browser.
02:25For example, I have a title up here that was actually replaced by some
02:28JavaScript--tried to make that reasonably obvious.
02:30Now if I right-click somewhere and click the option to View Page Source,
02:34which you'll get in any browser, the actual section that that originally was
02:39had the word Mission in it.
02:41So the View Source still has the old content.
02:43This is in the h1 called pageID.
02:46However, if I'm using Firebug, either in the DOM or in the HTML, and I can drill
02:51down into the particular sections that's in mainContent here,
02:54I've got the pageID with "This title was replaced by JavaScript."
02:58So Firebug is actually giving me the more up-to-date version, which is very
03:02useful if you're starting to manipulate the DOM in JavaScript.
03:05But the panel that we'll get more and more interested in is the script part of Firebug.
03:11That's telling me a message here that it's disabled right now.
03:14I'm going to enable it and then reload the page.
03:16And what this does is let me view all the JavaScript being used by this page,
03:21whether that's inline in the HTML, and I have a little bit here, and that was
03:26just to prove this point that some JavaScript actually in the HTML itself that
03:29it would show me. Or if I'm using a separate file, which I'm also doing,
03:34I can click on this dropdown menu here at the top, and it allows me to switch
03:38between the different files that have JavaScript in them.
03:41That's quite common that you'll actually see several files here when you're
03:45using this dropdown.
03:46And the best thing about this panel is that it will allow us to do
03:50JavaScript debugging.
03:51We would be able to follow this code as it runs.
03:55We can set breakpoints in our code to automatically pause when we're about to
03:59hit that line, allow us to read the current values of variables, and step through
04:03the code line by line to really understand what's going on.
Collapse this transcript
Going through a debugging session
00:00So here is an example debugging session.
00:02I'm going to open up a page that's given me problems right now.
00:06Now, it's not actually given me any JavaScript errors; in fact, the JavaScript is working.
00:10I have some script that's changing the message on this page every few seconds,
00:14and this seems to be working just fine.
00:15I can see that rotate. The problem is if I leave it long enough, we're hitting a
00:20message I wasn't expecting,
00:22undefined, which I can tell is something weird going on with JavaScript.
00:26So what I'm going to do is open up the Firebug panel, which if I didn't have
00:32it opened before, is likely to give me a message like this that the Script
00:35panel was inactive.
00:36I need to reload it to activate everything here.
00:39I can check that the console is giving me no errors, and that is the case.
00:42There are no errors.
00:43There are no messages here, and that's because my syntax is actually correct.
00:47There aren't errors in my syntax.
00:48There are errors in my logic, and I want the debugger to help me find them.
00:53So let me explain what I'm doing here.
00:55At the top of the page, line 1, I'm creating a message array with a few messages
01:00in it, just using the array shorthand. There are actually just three messages
01:04in it. And then I'm creating a variable that can hold my current position in the array.
01:09We start off with at zero.
01:11I then have a function called deeperFunction--
01:13we'll go into that in a moment-- another function called simpleFunction, and
01:17another function called changeMessage.
01:19It is best to explain these by going from the bottom up.
01:22Here I have the classic window.onload anonymous function, so after the page and
01:28all its assets are loaded, I simply run one line of code, a call to
01:32setInterval, which is going to set up a repeating call to the changeMessage
01:37function every four seconds.
01:40So I can now forget about the lines 31, 32, and 33.
01:43I know that changeMessage is being called every four seconds, and I can kind of
01:47tell that that's actually happening, because it is doing something.
01:52I could have written the code in the changeMessage function to do all the work,
01:56but to make it a bit more interesting, it's calling another function.
02:00This function is called simpleFunction, which is a little bit before
02:04here, defined on line 14.
02:06That runs and the first thing it does is call another function, so I'd go one
02:11more level deep into something called deeperFunction.
02:16Now, this function performs a loop.
02:18It goes around 500 times and just creates some random numbers here.
02:22Okay, in my example I've just got this code so I can have some code to play with.
02:27I don't actually do anything with those random numbers.
02:30But I know I'm going a few levels deep, and then here's the code that seems to
02:34be setting the message.
02:36So I know something about its working, so let's figure out what's going on.
02:40I'm going to set a breakpoint.
02:41Now you're allowed to set a breakpoint on any of the lines in the gutter here
02:45that are darker colors,
02:47and that really just means any lines that actually are JavaScript statements, that
02:51they're doing something.
02:52You can't set a breakpoint on a curly brace or on a blank line.
02:57So I'll create a breakpoint on simple function and I just wait.
03:00I don't have to reload, because a few seconds later this function is being
03:04called and suddenly I snap into Break mode.
03:07The line is highlighted in yellow and the icon
03:10is changed here with this little Play button, so we're paused.
03:13The code is now paused, nothing else is happening, the message isn't changing.
03:17I can now step through line by line, and to do that I'm interested in these
03:21buttons up here at the top right.
03:24We have the button called Continue, Step Into, Step Over, and Step Out.
03:30The first one is actually Rerun, but that's not relevant here.
03:33That allows you to quickly jump back in time and cause an event to happen again.
03:37It's not relevant for what we're doing, so we're focusing on the last four.
03:41Continue would simply say, go again till you hit another breakpoint.
03:46In this case, if I clicked it, we would run through the code and it would
03:49actually change that message again, and then we'd break on the next call to
03:53simpleFunction, but that didn't help me much.
03:55So what I want is this guy, the Step Into.
03:59Let me step line by line through the code.
04:02If I click it once, we're going to jump into the simpleFunction function, which
04:08itself calls deeperFunction,
04:10the first thing it does, so step into that, and itself its first line is this
04:15for loop that's going on 500 times.
04:18If I step into that we're executing the lines; in fact, if I just keep
04:22clicking the Step Into button, I can see that I'm going around of the loop
04:27potentially 500 times.
04:28If you notice that over here on the right-hand side, I have this Watch window
04:32that's actually telling me the values of the variables that make sense here,
04:36the local variables.
04:38In this case I've got a variable called foo, one called bar, and then the
04:42variable called i, which is my loop counter.
04:44If I don't have the Watch window open, I can also get to those by just
04:48mousing over the variable names and see the different values of those things,
04:52which is very useful.
04:54So I could continue on, but this is going to get a little tedious if I have to
04:57go around 500 times before I jump back out.
05:01If I know that I'm done here, because it doesn't look like there's a problem,
05:05I can come over and click the button that says Step Out.
05:09Now what Step Out is going to do is take me right back to whoever called
05:13deeperFunction, so one level back up,
05:17which was this simpleFunction call.
05:20And now I can continue on.
05:22I'm going to actually click Step Into again.
05:24This line creates a new variable to grab the message of the current position of
05:29the array. It then grabs a handle to the actual message on the page
05:34and then uses inner HTML to set it.
05:37Once I click Step Into this line, we should see that change up at the top of the
05:41page: yes indeed, there it goes.
05:43We then add want to messageIndex, which I mouse over is now two.
05:48Is message index greater than the length of the array? Now there's three elements in the array.
05:53And we don't need to reset it.
05:55I click Step Into again, and we go round about again.
05:58If I keep clicking Step Into, we jump back into the call to simpleFunction.
06:03Now I'm looking at that call to the deeperFunction again.
06:05I'm thinking I don't really want to go in there because that's going to take
06:08me to the loop of 500 times.
06:11Is there any way I can just execute and move on?
06:14Well, yes there is.
06:15It's this one here, the Step Over button.
06:19A lot of people make a mistake with Step Over the first time they come across it.
06:22Step Over doesn't mean skip.
06:25It means execute this code but if it's a function, I don't want to go into it;
06:31just do it and move on.
06:32So I'll click Step Over to execute deeperFunction without going into it. Then we
06:37jump to the next line. And this is saying that we want to grab a message,
06:42whatever is at this position 2.
06:44Notice that when I hover over new message, because I haven't executed this line,
06:48that is considered undefined; that variable doesn't exist.
06:51I click Step Into and I go back and mouse over, and now it does exist and it has a value.
06:58We move over again. We change the inner HTML.
07:02I'd add one to the messageIndex.
07:04It's now equal to 3.
07:06I ask, is the message index longer than the length of the array?
07:09No, 3 is not longer than 3.
07:11Okay, so I don't need to reset it, and that's my problem of course. Hopefully, at
07:15some point this clicks with me.
07:17The issue is the next time that I come around--
07:19I'll actually set a breakpoint here--
07:26I'm going to try and get whatever is at position 3 of the messageArray.
07:30Well, the messageArray only has three elements to it.
07:34That would be 0, 1, and 2. There is no position 3.
07:38So when that line has executed, newMessage is still undefined, and that's
07:43leading to our problem.
07:45This is a very common situation with arrays to be off by one, either one to
07:50few or one to many.
07:51You want to pay a lot of attention to those.
07:54So I can pretty much figure out here what the issue is with my code. What I
07:58really need to do is where this check is happening,
08:02I need to say if message index is greater than or equal to the length of the
08:07array, meaning I want to reset it if it's 3, not if it's 4.
08:12Okay, so I can turn off that breakpoint here and turn off that breakpoint here.
08:15But before I go and do that, I want to show you one more thing.
08:20Let's say we were worried about this code here in deeperFunction.
08:24There is something in here I'm interested in, but I don't want to go through 500 times.
08:28Well, I don't have to.
08:30A great feature is you can set a breakpoint on a line here, but then
08:35right-click it, use your context menu to see that this breakpoint only stops if
08:40this expression is true, and you can check the contents of the variable, so if a
08:44variable is equal to a particular value or greater than a particular value.
08:49In this case, I know I'm going to try and go through 500 times.
08:52I don't want to go through 500 times, so what I'm going to do is actually ask if
08:56the variable i, which is my loop counter variable that I'm creating here,
09:01I want to see if it's, say, a multiple of 100. The way I do that is i % 100 == 0.
09:12This is the percent sign, which is the modulus operator. It means i divided by 100,
09:17what's the remainder of that?
09:19So if i divided by 100 leaves a remainder of zero, I want to stop.
09:26I click Continue, and the first time through it is actually going to stop,
09:29because i is equal to zero. And it say if zero divided by 100 leaves a
09:33remainder of zero, which it does, we're stopping. But if I click Continue again,
09:39I notice that i immediately jumps to 100, so there is a hundred iterations of
09:43the loop that I didn't have to do. I click it again,
09:46we are at 200. I click it again, we're at 300.
09:49It's done all those iterations.
09:51I just didn't pause on any in between.
09:54And then I can come back over and just click the same area in the gutter to turn
09:58it off and click Continue.
10:00While Firebug can get deeper--and you should check out the documentation on
10:05getfirebug.com--just these abilities are being able to set breakpoints,
10:09these watch expressions, conditional breakpoints, if you like, and being able to
10:13mouse over these variables and step through your code will be enough to debug
10:17almost any JavaScript you're likely to see.
Collapse this transcript
8. Building Smarter Forms
Accessing form elements
00:00When it comes to working with forms, we care about several things:
00:04first, the values of the individual form elements, and then the events caused
00:09by those form elements when you change them or when you move in and out of
00:13them, and of course the event of the entire form itself, in particular
00:18submitting the form.
00:19Now, if you've given your form and the fields inside it their own IDs, then
00:24you can of course use document.getElementByID to retrieve either the form or any field in the form.
00:32And if the HTML for your form has either an ID or a name property--
00:37a name property is quite common with forms--
00:39you can use the following format too: document.forms.name of the form. In this
00:46case, it was frmContact.
00:48And if you use the name property in your HTML for your individual form
00:52elements, you can use that directly too, document.forms.name of the form .name of the element.
01:00But I'm still a fan of the good old document.getElementById.
01:05So let's talk about the individual form elements first.
01:08Probably the most common one is the text field, and as we've seen in the Events
01:13chapter, text fields have a value property.
01:17You can either get it or set it, and that's the same for a larger text area
01:22element if you're using those.
01:24Now, we've seen the onfocus and onblur events, that an element triggers onfocus
01:31when you go into it, onblur when you leave it.
01:34Now, onblur is always called when you leave the element, even if you
01:37didn't change anything, so there is also an onchange event if that's more to your liking.
01:42But the text fields also generate events for each keypress, in fact, three events:
01:47onkeypress--which is the entire press a key, then release it--but there are also
01:52events for onkeydown and onkeyup, if you need to get that granular.
01:58Now, when it comes to check boxes and radio buttons, rather than the value
02:03property of the text field, which wouldn't really make sense here, what we care
02:07about is the checked property.
02:08That's the main, most important property of the check box element, and
02:12that's either going to be true or false.
02:15Check boxes and radio buttons also generate an onclick event when they're clicked
02:20on and an onchange event. Most of the time you can use either or.
02:23And what about when you have to say a select field that contains many options,
02:28either showing as a dropdown list or as a list box itself that you can click in?
02:33Well, this can depend.
02:34See, in HTML you can have a select that only allows one selection or a select
02:39that allows multiple, and you can actually read this from the type property of
02:44that element, which will either be select-one or select-multiple.
02:48Now, for a single select, when you select an option of that dropdown list, the
02:54onchange event is triggered, and you can find out which option is selected by
02:59reading the.selectedIndex property of that element.
03:03Having said that, but if you have multiple, that's not enough. What you then
03:07have to drill down to is the options array of that select field and actually go
03:12through all its options one by one and figure out if they have a selected
03:17Boolean property for each individual one.
03:20That sounds tedious, but it can really be done in only a few lines of code.
03:25But what about the form itself?
03:27Sounds like it will be more complex, but really it isn't.
03:30There is one main event of the form, which is the onsubmit event.
03:35This is called when the user clicks-- not surprisingly--the Submit button,
03:38whatever has been defined on the form as the Submit button.
03:41Now, by subscribing to this onsubmit event, we can interrupt it before it
03:47actually gets sent to the server.
03:48You can check the boundaries of the fields and even prevent the form from
03:52submitting by returning false from the event handler.
03:57So this is a great way we can improve the client's experience by instantly doing
04:01validation on their machine without waiting for a roundtrip to the server.
04:06Now, don't rely on purely JavaScript to validate any form you have.
04:09The assumption here is if you're submitting information to a server, you should
04:14always be performing validation on the server side too.
04:16And let's see a couple of examples of what we can do with this.
Collapse this transcript
Preventing a form from being submitted
00:00I have a simple page here with a contact form.
00:04If I click the Submit button to send this, it's actually popping up this
00:08message, "Please provide at least an email address!" and it's stopping me from
00:12submitting the form.
00:13Let me show you how that's done.
00:16The form itself, my HTML, is nothing particularly special.
00:20It's a standard form.
00:22It's actually submitting just to a local page, but normally you would of course
00:25be submitting to a server.
00:27I am just going to come down towards the bottom where I have a place, just a
00:33span tag with an id of errorMessage, there is nothing in it right now.
00:38Over in my JavaScript, we've got a couple of simple things going on.
00:42Let's talk about the simplest one first.
00:43I have a window.onload event.
00:45That means when the document loads call the function called
00:48prepareEventHandlers, so we can forget about the rest of that. This function is called.
00:53What it's doing is saying that we want to handle the onsubmit event of the
00:59form called frmContact, and when that onsubmit event happens we're going to execute this code.
01:05It's written in an anonymous function here.
01:08That code says, if the email field is empty, so document.getElementById
01:14email.value equal to an empty string, we're going to set the innerHTML of that
01:21error message to, "Please provide an email address," and the most important thing
01:26here to stop the form from submitting would be return false.
01:30In fact, this is really all that I would need, although for best practice what
01:34I'm doing is saying no, if that wasn't empty, if there was something in the
01:37email field, we're going to reset that message if it did have anything in it and
01:42explicitly return true,
01:44saying yes, go ahead.
01:46So back over, into Firefox, when we click this without providing an email
01:52address, it doesn't submit anything.
01:57If I come up here and say test@null.com-- and yes, right now we could really put
02:02anything in here--then it immediately allows me to submit, which is just
02:08redirecting to a local page right now, but the concept is exactly the same, even
02:11if you were submitting to a server-side component.
02:14Make no mistake, the single most important piece of this whole code was this
02:21one, that when the onsubmit calls an eventHandler,
02:25we need to either return false to stop that submit event from going on any
02:29further, or return true and say, yes, I've run the script, just go ahead and do
02:34whatever you were going to do anyway.
Collapse this transcript
Hiding and showing form sections
00:00In this example, rather than react to the onsubmit of the form, I am actually
00:04going to react to an event of an individual form element--
00:07in this case, this check box, that when I check it is activating or turning on
00:12another section of the form itself.
00:15This is very, very simple to do.
00:17Let me show you the general process and a few best practices for doing this.
00:21So I am going to jump into my editor. The HTML here is very, very straightforward.
00:28The section that has multiple check boxes in it is wrapped in a div with an
00:32id of tourSelection.
00:33Now, there are no CSS or other styling properties being applied to it, so it
00:39actually isn't hidden by default, and that's quite important.
00:42We'll talk about that 'why' in a moment.
00:45So going into my JavaScript, just a few simple lines, and getting rid of the
00:50last three here, this is just a window.onload that is calling preparePage.
00:55So everything is in this preparePage function.
00:58This gets called once, and what we do is here.
01:02I'm volunteering to react to the onclick event of an element called brochures.
01:10This is the id of the check box in my HTML.
01:14So I'm just saying, when that gets clicked, we will perform this
01:18anonymous function.
01:19Of course, the click could be either checking it in on or checking it off, so
01:24the first check is, what is it? And we don't ask for a value here;
01:29I asked for the .checked property of brochures.
01:34I don't need to say is it equal to true or is it equal to false, because
01:39the.checked property is a Boolean.
01:42So just by putting this in my condition I'm asking, this is true,
01:45I don't need to say if true equals true,
01:47it's just, is it true? If it is, what I'm going to do is grab the div called
01:53tourSelection that contains all the other check boxes, and then--and this is the
01:57first time we've seen these properties--
01:59I'm using the .style.display property to drop into basically the CSS of this
02:07individual element and change that to block.
02:09Now, this is making it visible. This is the default way that it looks.
02:12If it's checked, I want to see it.
02:15If there was a change and it wasn't checked, I am going to set that the same
02:18property to none, to hide it.
02:21So we've associated this if statement with the onclick event of the check box.
02:27The only other thing that I'm going to do is because this function gets called
02:30once, after I have subscribed to that event, I'm going to then say, but then go
02:35right ahead and hide that div.
02:37Now, the reason that I'm doing it here in my JavaScript is yeah, I could do it in CSS.
02:43I could have actually hidden it in the HTML and CSS, but there's the problem.
02:48If somebody went to that page and their browser had JavaScript disabled, this is
02:54a much better way of doing it,
02:55what's often referred to as progressive enhancement, even though this is a simple example.
03:00We are using JavaScript to first enable certain behaviors.
03:05If the user doesn't have JavaScript, everything still works exactly the way it was before.
03:11But if they do have JavaScript enabled, we suddenly have a more
03:15interactive form.
Collapse this transcript
9. UI Enhancement
CSS and JavaScript
00:00You should of course already be using CSS to style your web pages, having a
00:05clean division between markup and presentation, just like we want a clean
00:09division between markup and behavior.
00:12And the great thing is JavaScript will allow us to make our presentation and our
00:16styles dynamic just like we can make the actual content on our HTML dynamic.
00:22And here's how we do it.
00:23The most direct way is that we can set inline styles on an element directly from JavaScript.
00:30Step one, as ever, is to grab the element using say document.getElementById, and
00:37then we use its .style property to apply a CSS style.
00:41And what we're using here are the same styles we'd use in a CSS document.
00:46So, for example, color equals red.
00:50And any acceptable value in a CSS file can be used here in our JavaScript, so we
00:55could use, say, hexadecimal colors instead,
00:58or myElement.style.left equals 40 pixels or .style.backgroundRepeat equals repeat-x.
01:06Now, one thing to note: you do have all the usual CSS style properties
01:11available, but they might have to be written a little differently, and here's why.
01:16So let's say we take an example of pure CSS in a CSS file.
01:20Well, it's equivalent to set in JavaScript. It looks kind of similar.
01:25We'd say myElement.style.width for width or myElement.style.color for color.
01:31But when it comes to font-weight in CSS, that becomes fontWeight in JavaScript,
01:38with the w capitalized.
01:40Same thing with background-color.
01:42So anything that would be written with a dash or hyphen in CSS becomes
01:47camelCased in JavaScript.
01:49You remove the dash and any subsequent word becomes capitalized.
01:52Now, this is not JavaScript just being different for the sake of it. Think about it.
01:57We can't put a dash in our code.
02:00That's how we subtract in JavaScript.
02:03And because there doesn't need to be white space between our operators,
02:06JavaScript here would think we're trying to perform a subtraction.
02:10myElement.style.background-color or font-weight just wouldn't work, so we do camelCase.
02:18Now, when you're setting these properties, you always set them as a string.
02:23And if they need units when written in CSS, you pass units in JavaScript, so
02:27notice that we have the width is equal to px for pixels.
02:32We need the leading hash, or leading pound sign if you'd prefer, for
02:35the hexadecimal colors.
02:36And one thing to take care of, if you're used to writing a lot of CSS and it's
02:42second nature to right say 230 px;,
02:46you don't want to put that semicolon inside the double quotes that you're
02:50setting the property to.
02:51Yeah, sure, we use the semicolon in JavaScript, but it's outside the quotes,
02:56to end the statement.
02:57Now, if you have predefined classes in your CSS file and you'd like to just use
03:02JavaScript to apply an entire class to an element, we can do that too.
03:06So we had myElement.style and we can think we might have myElement.class,
03:11but here's the problem.
03:12It's not just the word class. You see, class is a special name in most
03:18programming languages.
03:19It has to do with object orientation.
03:20And even though we don't use the word class in JavaScript,
03:23it is a reserved word, and you're not allowed to use it.
03:27So the property we actually set is className.
03:31Grab the element and set its .className property to whatever the name of your
03:36class is in your CSS file.
03:38If you need to clear it, you can actually clear just by setting it equal to an empty string.
03:44So let's see a couple of examples.
Collapse this transcript
Removing and applying CSS classes
00:00If you have a class defined in your CSS file, such as this one
00:04called.example, it's very easy to make this apply to a particular element in
00:10JavaScript; in fact, you'll spend more code saying when you want this to
00:14happen than actually doing it.
00:16If I look at some example of JavaScript, I have to apply this class called example.
00:21This is the only code that I actually need to write.
00:26Find the element, .className, =example.
00:32The only code that I'm wrapping around it here, not surprisingly, is being
00:36called when the document loads and just so I can have a bit of interactivity,
00:41I am going to respond to an onclick event on the div called mainContent.
00:45I am going to execute this anonymous function that actually asks, what is that
00:52class? Is that class currently set to example?
00:54If it is, I am going to blank it out.
00:57If it isn't, I am going to set it to example.
00:59So you've just got a little toggle on/off here happening.
01:03If I jump over and just open that up in the browser, right now that class is not
01:09being applied, but if I click anywhere in this main div, we're applying that
01:14class, which is actually setting this part of text to white, and just clicking
01:19back and forth. It's either applying the class or taking it off.
01:23Now, one thing to note, you can apply a class all you want, but it's still using
01:28the cascading rules of CSS, which means if there are more specific rules being
01:34applied to some of this content, say through ids or even inline styles, the
01:40closer ones are going to win.
01:42So in this case what it looks like we're doing is we are being successful in
01:47applying the color--white--to the headline, but it looks like the paragraph
01:52probably has its own color being set a little closer to it.
01:56It doesn't look like font-size is making any difference, although we do have 1em there.
02:00Text-align right certainly looks like its being applied.
02:04Again, this all comes down to normal CSS rules.
02:08JavaScript applying a class is pretty much the same as manually applying that
02:12class in your HTML when the page loads.
Collapse this transcript
Changing inline styles
00:00So I'm going do something a bit more interesting to this page, using inline styles.
00:05Let's say we're trying to get people to sign up for our newsletter.
00:09The page itself is pretty normal.
00:12I do have a section of it that's been defined as a div with an ID of join,
00:17which is trying to get people to sign up for the monthly newsletter.
00:21Well, what I'm going to do is a little bit of JavaScript to make this stand out a bit more.
00:25I'm going to jump over into my JavaScript file.
00:28Let's get rid of the easy code.
00:31Down at the bottom, I have a window.onload
00:34that's going to call a setTimeout function that passes in beginAnimate, 5000.
00:39That simply means do a single call to the beginAnimate function in five seconds
00:46after the page is loaded. What does that do?
00:49Well, up here in beginAnimate what I'm doing is I've got three lines that all
00:54grab that actual div, which currently is part of the body of the page.
00:58What I'm going to do is a couple of CSS style tricks.
01:01I'm going to set its position to absolute, then its left position to 0 pixels,
01:07and its top position to 100 pixels from the top. Well, then what?
01:12I'm now going to call setInterval, and this is the repeating timer event that's
01:18going to call the animateBox function about 20 times a second.
01:24And if you remember, setInterval gives you back a variable, it gives you back a
01:28handle to that interval, which I'm just going to store in intervalHandle, which
01:32is defined as a global variable up here.
01:36So, really all the work is happening in this function called animateBox.
01:41First thing it does is say, whatever the current position is I'm going to add 5 to it.
01:45In fact, the first time this ever gets called current position will be 0. So we add 5 to it.
01:52I then grab that div and set its style.left property to whatever the current
01:59position is, and then I'm going to use the plus sign and add px, remembering
02:03that we have to pass in any units that are used by that CSS style--in this case, pixels.
02:10Now, currentPos is actually a number, but px is a string, so it will concatenate
02:16these together as a string.
02:17So it will be 5 px, 10 px, 200 px, and so on.
02:22And all that I'm doing here is saying, if the current position, the leftmost
02:27position, gets to be greater than 900-- and bear in mind what I'm checking here
02:32is just the number variable without the px, that's fine--
02:36I'm going to clear the interval, and it makes it so that this function doesn't
02:40get called anymore, and then I'm going to reset the div to its original styles.
02:45Really, I'm just going to pull off any custom styles that I applied up here in
02:50the beginAnimate section.
02:52Not an awful lot of code, and let's see what impact it has.
02:57I'll jump back over and I'll just open up this page.
02:59Well, after a few seconds what's going to happen is our little thing that we're
03:04trying to push is going to pop over and make itself rather annoying.
03:10And yes, indeed, we're using our powers of JavaScript for evil here.
03:14If you note that after it crosses the screen, it has actually jumped right back
03:18down to the bottom here, just as it normally was.
03:21And I don't recommend doing this on a regular site;
03:24you're just going to annoy people. But I think it's a pretty good example of in
03:29just a few lines of code that you can really significantly manipulate some of
03:36the content that you have on your page, and using the ability for JavaScript to
03:41talk to CSS, even in just a few simple properties, can be very powerful indeed.
Collapse this transcript
10. JavaScript Best Practices
Understanding JavaScript style
00:00When we talk about style with programming languages, we're moving away from the
00:04rules of how you must and must not write JavaScript into more of how you should
00:10and shouldn't write it.
00:11So how should you name your variables, where should you put your braces, what
00:15should you call your functions, and where should they be placed in your code?
00:20Because this matters.
00:22Style decisions matter for you and for other developers on your team.
00:26You want your code to be readable, you want it to be consistent,
00:29and you also kind of need to play along with how everyone else in the world is
00:33writing their JavaScript, because that's going to make it easier to read
00:36example code and read books and, more importantly, recognize whether that code is written well.
00:42And style matters simply because JavaScript is the most publicly viewable
00:47programming language in the world.
00:49Unlike a desktop application, with JavaScript running on a web page, all your
00:53code is sent to whoever requests it.
00:56Every client's browser gets a copy of your JavaScript in plain readable text.
01:01Sure, most people won't look at it, but they could. They can view source.
01:05They can use tools like Firebug to get to it. Other web developers can see how you write your code.
01:10So think of all the JavaScript you write as effectively being published on the
01:15web and get into good habits early.
01:18So what are these good habits? Well, let's begin with some naming conventions.
01:21We get to choose names for variables, functions, even objects, if you
01:26define your own objects.
01:27Now, the rules of JavaScript say you must use letters, numbers, dollar sign, and
01:32underscore, and you can't start with a number, but that doesn't mean that
01:36something like this would be a good name for a variable. We want clarity.
01:41We want readability. We want meaning.
01:44Yes, okay, when we're learning, we use placeholder names a lot:
01:48var a, var b, var c, x is a pretty common one, or common meaningless words like foo or bar.
01:57But our real JavaScript variables will represent meaningful information:
02:02the name in a textbox, a date, the height and width of an image, or a collection
02:06of element nodes that represent the links in a menu.
02:08So naming conventions have developed over the years, and these days the dominant
02:14way JavaScript is written is this.
02:16Variables and functions, which will be most of what you name yourself, are
02:20written in camelCase.
02:22The word would start lowercase.
02:24If it's just one world like score, it would be all lowercase. But with
02:28multiple words you capitalize the first letter of each subsequent word, like
02:33the hump of a camel.
02:35Multiple words are not separated with underscores as they might be in some other
02:39programming language.
02:41Functions are named the same way, or methods if they're in an object.
02:45Now, these are typically multiple words for clarity and often in a loose verb noun format.
02:52Think of the way that we work with the DOM:
02:54createElement, appendChild, getElementById.
03:01When we're working with objects, the convention here is to also capitalize the first word.
03:07And quite often objects only aren't one word. Think of the way we've seen
03:10objects in JavaScript, like the Math object and the Date object and the Array object.
03:15Now, bear in mind, we still use camelCase too. After all you create a variable
03:21that uses camelCase that's based on an object that capitalizes the first letter.
03:27Now, if you're coming from a language that uses underscores a lot, or
03:32prefixes variables with an abbreviation that's meant to represent the type of information,
03:37you can argue against camelCase as much as you like.
03:40There is nothing stopping you from using your favorite naming style, but
03:44camelCase is the dominant style for JavaScript.
03:47It is what's recommended by the Yahoo!
03:49style guidelines, by the Google style guidelines.
03:52It's what's used by the popular JavaScript libraries, like jQuery and Prototype,
03:57and of course it's what's used by the DOM methods themselves. There is no
04:01escaping camelCase in JavaScript.
04:04Let's talk about brace style, where to put the opening and closing curly braces.
04:08The dominant style in JavaScript is the most traditional brace style for C-based languages.
04:13If you have an if statement or a while loop, the curly brace opens on the same
04:18line as the keyword, as the if or the while or the for.
04:22The code is indented inside the block, and the closing curly brace is on a line by itself.
04:27If you're adding an else to a if statement, you'll typically see that continued
04:31on the same line, again, with the opening curly brace of the next section on the
04:35same line as the keyword.
04:37Now, there are other ways, like Pascal or Allman style, when the opening braces
04:42on its own line and lines up with the closing brace, but I avoid this style in JavaScript.
04:48Now, while it wouldn't matter in most languages, in JavaScript you can run into
04:52a situation with JavaScript's own ability to insert what it thinks are missing
04:56semicolons on lines that don't have them.
04:58It's a rare issue, so I'm not going to get into specifics, but if I use the style
05:02on the left, I don't have to worry, and it is the standard style.
05:06So for all your ifs, your whiles, your functions, all of these constructs,
05:11open the curly brace on the same line as the keyword, the while, the for, or the function.
05:17And while we're talking about blocks of code, as in other C-based languages, if
05:22you have say an if statement that only does one thing, you can technically
05:27remove the curly braces.
05:29If there is one statement after the if and the condition, it behaves as if there
05:34are curly braces around it.
05:36But, as in other C-based languages, it's a really bad idea to do this, because
05:40later on it's super easy to add a line of code to this.
05:45And when you read this code what you think you're getting is this kind of block,
05:50where if x is more than 500 we're going to execute these two lines, but if we
05:54left the braces off, what we're actually getting is this.
05:59If the condition is true, we will pop up the alert and we will always then go
06:03ahead and reset everything. And these kind of bugs can be a real pain to
06:08recognize, so always use the curly braces, even for one-line blocks.
06:13Now, another general rule here is even though you don't have to define your
06:18functions before you call them--so, for example, here I've got one function
06:23called some function that called other function, and other function is nicely
06:27defined after it in our code file-- the preference and the best practice is to
06:32define your functions before they are called.
06:35In some languages you have to do this. In JavaScript you don't have to, but it
06:39does make for more readable and more usable code.
06:42So to review, we can really keep a few simple rules in mind:
06:46Use camelCase for variables, functions, and methods, and this will be the
06:49majority of what you have to name yourself.
06:53Open curly braces on the same line as the keyword.
06:55Always use blocks, even if there's only one line.
06:59Define your functions before you call them.
07:01And a couple of things we've been talking about along the way:
07:04always use semicolons to end a statement--even if you might not have to, you
07:09should--and always use var when declaring a variable.
07:14We could go deeper than this with style, but that's enough to get us started.
07:17If 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:24have been created by the JavaScript developers at places like Yahoo!
07:28and Google and Mozilla.
07:30Now, I don't have a personal favorite, but if you're after something more
07:33formal, just take a look at these and be consistent about the way you write
07:38your code.
Collapse this transcript
Minifying your code
00:00If you have ever looked at the source of a web page, you might have seen some
00:03code that looks like this, all squeezed together and essentially unreadable.
00:08Now this is actually JavaScript here, but that doesn't mean somebody wrote it this way.
00:13This is the result of minification; the code has been minified.
00:17This is a process to go through some regular JavaScript and minimize it to compact it.
00:23We would first start by removing comments. Then we might rename long variable
00:28names and function names to shorter names,
00:31then get a little line breaks, and start to combine multiple statements onto one line.
00:36Now, minification is done for one reason, to decrease the size of the JavaScript.
00:44The reason that you do it is to improve page load times, because the script
00:49gets downloaded faster.
00:50The two things minification is not: This is not compiling your JavaScript into a
00:55machine code, or anything like that.
00:57It is functionally identical.
00:59It's just a smaller amount of characters.
01:02And number two, it's not intentionally scrambling it.
01:05Yes, minified code is ugly, and it's tougher to read, but that's not why we do it.
01:09It's not for what's called obfuscation.
01:11Now the question is, how do you do this?
01:14Well, you could do it yourself obviously, but that would be very, very tedious,
01:17so there are lot of minification tools for JavaScript out there. Some of the
01:22better knowns are JSMin, the Yahoo UI Compressor, and Google Closure Compiler.
01:29Now many of these are command line tool. They are actually written in C or in Java.
01:33You can just download them and run them from the command line.
01:36Well, there are a couple that can be accessed over the web, like the
01:39Google's Closure Compiler.
01:40Let's take a look at that one.
01:42Google's Closure Compiler can be downloaded so you have your own copy, but
01:46there's a version available on the web, at closure-compiler.appspot.com.
01:52What I really need to do is to grab some JavaScript of mine to minify.
01:56Well, I have some just sitting in my editor here.
01:59I'm just going to select all of it, jump back over into Closure Compiler,
02:05and paste it in there.
02:06So it's regular JavaScript.
02:08There is nothing particularly special about it. And I am just going to go ahead,
02:11leave all the settings as is, and hit Compile. And over here on the right-hand
02:17side I can see that it's actually shrunk it a bit. The original size was 1.12K,
02:23and the compiled one is 595 bytes.
02:26Okay, we are not really starting off with a big file, but you can see the point
02:30of what's happening. The comments have been stripped out, some of the whitespace
02:33is gone, and it seems that we've done a little bit of tweaking here.
02:38However, we can take this a little bit further down. Over on the left-hand side
02:41I can choose to do an advanced setting for the Closure Compiler, hit Compile
02:46again, and that shrinks it down even further, to 479 bytes.
02:51Now in fact, Google's Closure Compiler is not just a strict minifier.
02:56It does have a few abilities inside it to detect code that might not be called.
03:01So it's definitely an interesting one to run your code through, because it tries
03:04to do some optimization and not just minification here.
03:08But that's mainly what I'm interested in it for. So I could either grab this and
03:13just copy and paste it, although if you see, it's also giving me a copy of a file
03:17which I could actually just download here at the default.js link.
03:22Because the whole reason is that we as developers need the comments, we
03:26need that whitespace.
03:27We need the meaningful variable names.
03:29The browser doesn't need it in order to run it.
03:32It's quite happy with the compacted version over here.
03:35So two things with minification:
03:37You only do this when you're happy that your script is correct, you pretty much
03:41only minifiy at the end.
03:43And two, of course, you keep a copy of the original for when you need to change it,
03:48because while you can unminify to an extent--you can get some white space back--
03:53there is no way to get back a comment
03:54that doesn't exist anymore, or know what a renamed variable was originally called.
04:00Now as we will start to see a little later on, it's very common to find
04:04third-party JavaScript libraries available to download in both the minified
04:09format, such as here jQuery, that when it's minified and zipped, it's 31K,
04:14whereas, the regular version is 229K.
04:17You would end up using the minified one on your site to make for a quick
04:21download, but you can always download and view the non-minified one if you
04:25want to read the code.
Collapse this transcript
Using JavaScript code checkers
00:00Just as we can run our JavaScript through a separate program to minify it, we
00:04can also run it through another program to check its quality, and to check it
00:08for common problems.
00:10Now in contrast to minification where there are many different tools to choose
00:14from, there is one best known JavaScript code quality checker, which is JSLint
00:19by Douglas Crockford, whose the JavaScript architect at Yahoo!
00:23You can find this at jslint.com.
00:26With this what you can do is take some code--I have got a block of JavaScript
00:29here--I'm just going to copy, take it over the JSLint, paste it in there, and
00:34click this button that says JSLint, to check it.
00:38Now, when you do this it's going to complain about a lot.
00:41JSLint will point out every little thing you do that isn't perfect, from the
00:46amount of whitespace you use between your operators, to how many characters
00:50you indent your code, to whether you declare all your variables using var,
00:54whether you are declaring your functions before you use them, and a thousand other things.
00:58I can see that just with this little amount of code I have got a whole bunch of problems here.
01:03Now these errors have nothing to do with whether or not your code actually works.
01:08It might work just fine and JSLint will still complain about a hundred different
01:12things in 10 lines of code.
01:14This is quite similar that if you take a web page that you know works perfectly
01:17well and run it through a formal HTML and CSS validator, you're typically going
01:22to find a bunch of things that technically aren't valid.
01:25It's kind of the same thing here. And as with HTML and CSS validation, if you
01:30take the time and fix all those little things, it will make your code better,
01:34but there are a couple of features to be aware of,
01:36so to not get frustrated.
01:38First off, we look at these errors, but we start at the top and work down.
01:43You don't pick and choose ones here.
01:44So we are starting off, problem at line 9 character five, missing use strict statement.
01:50Now this is an interesting one.
01:52In ECMAScript edition 5 there is something called Strict mode.
01:56It's an instruction to the browser to not even allow sloppy JavaScript.
02:00It requires the use of var for variables.
02:03And JSLint wants us to use Strict mode, even if we are just
02:07writing ECMAScript 3.
02:09Now I could do this in a couple of ways. If I actually added inside my functions
02:14just a line, say here,
02:18that was "use strict" inside double quotes, and just ended with a semicolon.
02:24It looks little strange here because we are just putting in a string, and that's
02:27intentional, because ECMAScript 3 doesn't really understand this, and all it's
02:31going to see here is a string literal and just ignore it.
02:34But the very up-to-date browsers actually do recognize this as trying to
02:38enforce Strict mode.
02:40However, if I click JSLint, what I will see is okay, our first error is gone,
02:45but if I go down a little bit, I'll probably find it somewhere else.
02:49There we go, Missing 'use strict' statement, if I didn't add that
02:52to all my functions.
02:54Well, if I know what it's complaining about, what I can do is come down towards
02:59the bottom of JSLint and here I find a whole bunch of options that I can check
03:04to allow JSLint to tolerate certain things.
03:08And one of them is the Tolerate missing 'use strict' pragma that use
03:13strict instruction.
03:14So I am going to check that and click JSLint again.
03:19I still have some errors here. The next one,
03:22Problem at line 10 character 5:
03:23'document' was used before it was defined, and then it complains that the line
03:28is a document.getElementById.
03:31Well, this is pretty common stuff.
03:33The reason that it's actually doing it here is, as you know, JavaScript was
03:37intended for the browser, but isn't always just used in the browser, and the
03:41document object only makes sense if we know that we're in a browser.
03:46So back down to the Options, and I'm checking the one on the left here that
03:50says Assume a browser.
03:52We run JSLint again.
03:54We've gotten passed that issue, but we still got problems.
03:57This next one here, Expected 'intervalHandle' at column 5, not column 1.
04:02Well, what does that mean?
04:03Here it's literally just complaining about the correct level of indentation.
04:08If you see that this line beginning intervalHandle equals is inside our
04:12function, but it's not indented the same way that the rest are.
04:15It should be indented with four spaces.
04:18That's what JSLint likes.
04:20So if I do that, we run JSLint again, and we go on.
04:24Now quite similar to that, what you'll see is there is a lot of complaints here,
04:28missing space between comma and number.
04:31It likes us to leave a space after the comma between parameters.
04:35Again, we don't have to.
04:37This is not going to change how the code works, but it's got its own set of
04:40presentational rules.
04:43Missing space between current position and the plus equal sign. What it's
04:49complaining about there are, for example, things like this line here, where it
04:54lacks a single space around the operators.
04:58Now what you'll often find is that JSLint will complain about a lot of this, so
05:02one of the other options I could do, if I don't want to fix everything right
05:05now, is I could allow it to tolerate messy whitespace.
05:10So I am going to go back and run it again.
05:12Well, we are getting smaller here.
05:14Problem at line 13 character 34, animate box was used before it was defined.
05:20What does that mean?
05:21Well, we are calling this setInterval function passing in animateBox.
05:28The issue is is the function animateBox isn't defined to later on in the code.
05:32Again, while this will work, best practices say that our function should be
05:36defined before we write code that use them.
05:40So this function animateBox should be defined before I use it in an argument.
05:44So what I am going to do is cut the entire function, and I just take it up and
05:51paste it in here, and then we run JSLint again, and we're getting okay
05:56there, we are getting down.
05:57Next one, it's saying, Type confusion, number and string, and the line it's
06:02complaining about is this, where we are actually concatenating a number, which
06:06is current position, and the string px.
06:08Well, in fact, I know this is okay.
06:10This is what I want to do.
06:11I am actually trying to create a string that says 200 PX or 300 PX,
06:17so I am absolutely fine that that happens.
06:20So I need to also go and tell it down here to tolerate type confusion.
06:28JSLint. I could just ignore that as well. And now finally, we have something here
06:32Problem at line 21, character 9:
06:34something was used before it was defined, and this I just added so we could
06:38actually see a problem here.
06:40And the problem is that I just start using a variable, something = something +1.
06:45Well, this should really have been defined somewhere else with the term var, but
06:49it hasn't been defined probably.
06:51So I could either delete the line that says something = something + 1, or I
06:56could go and define the variable up towards the top, so it's accessible there, or
07:01even somewhere else in the function.
07:04And then we have no errors. But as you can see, JSLint will always complain
07:09about your code, so try not to be too upset when it complains about every single line
07:13that you've written.
07:14It is very picky indeed.
07:16It's supposed to be picky.
07:17That's what JSLint is designed to do.
07:20But as you become comfortable with JavaScript, it's a really good exercise to
07:24make the effort to understand what it's complaining about, even as--what I did, I
07:30kind of ignored a of few of those errors and told it to be tolerated, at least I
07:34understood what its problem was.
Collapse this transcript
11. JavaScript Libraries
Introduction to JavaScript libraries
00:00JavaScript is a small language.
00:02We really have covered most of it already.
00:05But unlike technologies like Java or .NET or Cocoa, it doesn't have dozens of
00:10built-in libraries with thousands of objects for us to use.
00:13So we are now at the point where we need to start thinking about writing a bunch of code.
00:18But you know the things that we want to do with JavaScript are probably not all
00:22that different from what other people have wanted to do with JavaScript over the years.
00:27And the great thing is some of those people already wrote a lot of the code
00:31you need and bundled it together into the form of one of many JavaScript libraries.
00:37Now a JavaScript library simply means a bunch of JavaScript somebody else wrote
00:43so you don't have to.
00:45So what are these libraries?
00:46There are dozens of them. Here's just a few.
00:49Some of these libraries, like Google's Closure Library or MooTools or the Yahoo!
00:55YUI Library, are considered general-purpose JavaScript libraries.
01:00They have a whole lot of functions that help with navigating through the DOM.
01:04They include code for cross-browser detection, so it's easier to work with
01:08events without worrying about which version of Internet Explorer your user might have,
01:13or working with animation. They make it easy to have your JavaScript request
01:17information from a web server, then update the page when it gets a response,
01:21something often referred to as AJAX.
01:23To use any of these libraries, I just simply go there and download it.
01:28jQuery here, for example, gives me an option of choosing the minified version or
01:33the full development one.
01:34It is just JavaScript.
01:36You just download it and link to it the same way you'd link to a file of your own code.
01:41It is just JavaScript, so technically you're not getting anything you
01:44couldn't have written yourself, but it might have taken your months to write all this stuff.
01:50Now on the other hand, some JavaScript libraries are more specialized. Rather
01:55than be general purpose, things like Lightbox are simply JavaScript libraries
01:59for popping up images on your web site.
02:02You've probably seen these ones before.
02:05They might be for slideshows.
02:07They might be for implementing things like drag-and-drop and working with accordions.
02:13They could be as simple as a library that just helps you add curved corners to your divs.
02:19Now most of these libraries are open source and they are free.
02:23There is no licensing.
02:24You simply grab the code and use it, do whatever you want with it.
02:28So I encourage you to explore what's available, and new ones are
02:31appearing all the time.
02:33Now if you go back a few years, there was a lot of competition between the
02:37different libraries, but a clear winner did emerge.
02:41And the most popular general purpose JavaScript Library, by a mile, is jQuery.
02:46We are going to talk about this one shortly.
02:48Now I occasionally have people ask if they should avoid these libraries
02:53and whether real JavaScript programmers, whatever that means, write
02:56everything themselves.
02:57And the answer is absolutely not.
02:59Knowing the JavaScript libraries, particularly jQuery, is a core skill for a
03:04JavaScript developer these days.
03:06It's part of the landscape, and as soon as you've gotten a basic knowledge of
03:10JavaScript, like the one we have got so far, you'll want to start exploring these libraries.
03:14They really will make your life easier.
Collapse this transcript
Linking to multiple JavaScript files
00:00So I have suggested that your default way of including JavaScript on your page
00:05is to have a script tag right before the closing body tag that just links to a
00:09separate JavaScript file.
00:10And it is also quite common to see several script tags here, and particularly
00:15common when it comes to having both your own code and one or more JavaScript
00:19libraries and perhaps a link to a Google Analytics JavaScript and so on.
00:23But two things to keep in mind:
00:25you want to keep the amount of script tags here at a minimum, and the order of
00:30them matters. So, why minimum?
00:33Well, just be aware that every JavaScript file you link to is a separate request
00:38the browser needs to make to the web server.
00:40The browser gets the HTML and moves down through it.
00:44It sees the link to the JavaScript and makes a call to the server for that
00:48first JavaScript file.
00:49It then waits for that file to finish downloading, and then, and only then, moves
00:55on to the next one, calls the web server for that file, and waits again.
01:01And that order continues.
01:03It doesn't download the JavaScript simultaneously.
01:06It will do it sequentially.
01:08And that means the more files you have the more requests the browser needs to
01:12make and the slower your page is going to load.
01:17So while you might find it easy when writing JavaScript to have multiple small
01:21files, it's definitely worse for the user.
01:24So combine your JavaScript where you can.
01:27You should have as few JavaScript files as possible.
01:31And secondly, the order of the script tags matters.
01:35If you have a file of JavaScript that inside it calls a function in a second
01:40JavaScript file, well, you want to make sure to load that file before the code
01:44that tries to call this.
01:45This is very common with libraries.
01:47If you're using, for example, the jQuery library, you want to make sure that you
01:51load jQuery first before any JavaScript that might actually try to use jQuery,
01:57and the same goes for any other dependency.
01:59So sure, you can't always get this down to just one file, but you should
02:04certainly be very careful if you see this growing to seven or a dozen, and see if
02:08you can't combine some of them together.
Collapse this transcript
Introduction to jQuery
00:00jQuery is the most popular JavaScript library by far, and it really does
00:05make JavaScript easier:
00:07easier to navigate and manipulate the DOM, easier to add events, easier to
00:11work with animation, and really to do the same things we have been doing all
00:14along but with less code.
00:16So how do you use it?
00:17Well, very simply, what you need to do is go out to jquery.com and just
00:23download the JavaScript.
00:25You will find that even from the homepage you have a choice of either the
00:28development version, which is just the fully readable JavaScript, or a
00:32production version, which is 31k after its been minified and gzipped, so it
00:38really doesn't add much weight to your web site.
00:39I have actually gone ahead and downloaded both versions to the current folder
00:46that I am working with, but I only need the minified one.
00:49I have no intention of changing or even reading the other code. And then if I
00:54want to use it in my HTML page, I'm simply going to go in and add a link to it.
01:02In this case, I'm linking to the minified version.
01:05Now you could certainly make an argument here that it's possible to load jQuery,
01:09or any other library, with the script tag up in the head of your document. And if
01:14I thought I needed it as soon as possible, I might do that, but I'm pretty
01:19confident that I can load it down here just fine, though I am making sure that I
01:23am loading the jQuery file before any of my own code that might use it.
01:29So what do we then do with it?
01:30Now let's start with something simple.
01:32Without jQuery, we'd often write lines of code like this:
01:37document.getElementById, give it the name of an ID from the HTML, and then work
01:42with methods, or in this case a property.
01:44I am setting the className= "highlight."
01:47With jQuery, I might write this instead:
01:50The word jQuery with a lowercase J and an uppercase Q. In the parentheses
01:56here, I'm using the number sign or pound sign or hash sign, depending on which
02:01country you're from, and then myDiv to indicate that this is an ID.
02:06This is the same way we do this in CSS, and then a dot and then addClass (" highlight").
02:12So you might think well, so what?
02:13A little less code, big deal.
02:16But here's where it gets interesting.
02:17There are two reasons why the jQuery version is preferable.
02:22First, with getElementById we need this element to have an ID of myDiv in our
02:29HTML, and if it doesn't have an ID in the HTML, we can't get to it, but jQuery is
02:36much more flexible that that.
02:37We can give jQuery an ID to find by using the hash or the pound sign, but we can
02:43also find other parts of the page that we can't get with getElementById.
02:47For example, we can get all the elements with a particular class just by using
02:53the dot, the same way we would in CSS.
02:56We can get all the elements of a particular tag, like all the paragraphs or all
03:01the anchors or all list items.
03:04Now this piece in parentheses is known as the selector.
03:08We are telling jQuery what we want it to find, and the selectors are really
03:13borrowed from CSS, which is why we use a pound or hash for an ID and a
03:17period for a className.
03:18And unlike getElementById, which will only work on one individual piece,
03:23anything we do with jQuery will automatically work on all of the elements that
03:27match the selector that match what we are looking for.
03:30Now we can even refine it more than this.
03:34We could combine a couple of these.
03:35For example, in this case, p.description, give me all the paragraphs that have a
03:41class of description already on them. And there are also certain words we can
03:46add to further refine this like :first, :last, :contains, :visible.
03:54The way these would be used, again, is combining them with other parts of the selector.
03:59So let's take a look at how.
04:01So I have switched over to a file of some JavaScript, which I have mostly
04:05commented out here, so I can go through this.
04:07Right now, we are using the standard DOM way of getElementById, which is going
04:13to apply a CSS highlight to this main section here, main article.
04:18It looks kind of ugly, but it's proving the point that this actually works.
04:21Comment that one out.
04:23The JQuery version here would just be finding the div and adding the class of highlight.
04:28We are going to get more into why this is better in just a minute anyway. But we
04:32can get more flexible than that.
04:35I can simply say JQuery.tourdescription to find all elements with a particular class.
04:41Jump back over to the web page and refresh it, and I can actually see that that
04:46class is being applied to several different elements on the page.
04:53Similarly, I could apply that class to all the elements that were list
04:57items just by doing this.
04:58This doesn't use the pound sign or the dot;
05:01it just says li or p or a for a list item or a paragraph or an anchor tag.
05:08Refresh that page, and we can see that both here where I got list items and
05:13down at the bottom
05:14it's looking rather ugly, but it proves the point here that it is actually being
05:17applied to multiple elements at the same time.
05:21We can take that a little further, commenting that one out and then adding the :last to it
05:27we will first find all the list items in the entire DOM and then we'll add the
05:33class to the very last one.
05:35If I refresh this, now we can see that that works as well.
05:41And I can go even better than that. Using the :contains word in jQuery,
05:47we can tell that our selector will find all paragraphs and then filter them
05:51down to say only the ones that contain the word 'packages' and then add the class of highlight.
05:57So saving that, refreshing the page and scanning back up, I can see that
06:02it's applying that class to several of them, as long as the paragraph
06:06contains the word packages.
06:08So with jQuery, there are many ways to get immediately to very specific parts of
06:13the page without needing an ID on them.
06:17So with the selector, we are telling jQuery what to look for.
06:20Then we have a dot, and then we tell it what we want to do, some action, some
06:25change that we are doing.
06:26In this case, jQuery find the ID of myDiv and then add the class of highlight.
06:33Now the second reason why this is better is that addClass is much more flexible
06:39than just using className with our document.getElementById.
06:44See, when we use className it's a property. We're just setting it; it will
06:48overwrite any classes that were there before.
06:51But when we use addClass with jQuery it adds our new CSS class and keeps
06:57any that were there before, so we can start stacking our CSS classes up on our elements.
07:02And not only do we have an addClass,
07:04we also have a removeClass method in jQuery and a toggleClass method in jQuery,
07:09which means if the class is not there, add it;
07:13if it is there, remove it. And this is a great little microcosm of what
07:16jQuery is all about.
07:19It's more accurate. It's more flexible.
07:21There are more choices.
07:22It's kind of what you wish JavaScript did in the first place.
07:25Now we can make our code even shorter.
07:28If you think that typing out jQuery might get a little tedious because it's easy
07:32to get the casing of this mixed up, there's a shortcut so we don't have to.
07:36We simply replace the word jQuery with the dollar sign.
07:41So the general format we are going to use with JQuery is the dollar sign and
07:45then in parentheses the selector, or what to find, then a dot, and then some
07:50action in any parameters we have to pass about what to do, what do we want to do?
07:54So what does the dollar sign mean?
07:56Well, the dollar sign is just an alias, a shortcut for jQuery itself.
08:00Unlike languages like PHP, there is nothing magical about the dollar sign in JavaScript;
08:05it's just one of the accepted characters in the variable name.
08:08Dollar sign here is just a really short variable name that points to jQuery.
08:14So what else do we have?
08:15Well, we have some great ways of working with effects.
08:19So I am going to just uncomment this line of code here at Line 22, which is
08:24going to use the dollar sign for jQuery, tell it to find all paragraphs, and
08:28then call hide with the parameter of 4000.
08:33Saving that, I am going to jump over to the browser and then just refresh this page.
08:40Okay, I might not always want to do that, but what hide is doing, as you can
08:44probably tell, is taking 4000 milliseconds, or 4 seconds, to hide all paragraphs.
08:51And the great thing is jQuery is taking care of animating all this without us
08:55worrying about set interval calls or set timeout calls.
08:59So we have got hide. We have got show.
09:01We have got slide down, slide up, fade in, fade out, all just as easy to use.
09:07And then there are events.
09:08Working with events in jQuery is very simple indeed.
09:12If I just uncomment these pieces of code here, we can use the same selectors
09:17the dollar sign, in this case an ID of pageID.click, and in this case, passing
09:22it an anonymous function.
09:23Now what's this one going to do?
09:25Well, it's easier to show.
09:27Jumping back over and refreshing this page,
09:30when I click on word TOURS, it just changes to You clicked me!
09:33We are using the #pageID to add the click event and using that same selector
09:41and using the text method here to set its text value, rather than having to drill
09:46down into the individual text node.
09:49Again, very easy to add an event and very easy to start manipulating that DOM element.
09:55Not only that, but jQuery is also very conscious of the word 'this.'
09:59So if we use jQuery to add, for example, a click event to all the h2 elements,
10:08we can then be smart enough to know which ever particular h2 is clicked will be
10:13considered this every time that this function is called, meaning what?
10:19Jumping back over to the browser, as we scanned down, I know that these are h2s
10:23and when I click each individual one, it knows exactly what caused that event to be raised,
10:30so it's smart enough to know which one gets changed.
10:35And very simply, we could combine both jQuery adding events and combine
10:39jQuery's animation, so that very easily, refreshing this page, every time we
10:44click on the paragraph,
10:46it's smart enough to just disappear and fade out.
11:00And one last thing here,
11:01we are familiar with using window.onload to call some script when we know that
11:07the DOM is fully loaded.
11:09One of the problems with window.onload is if you accidentally write it multiple
11:13times, only the last one will be paid attention to, whereas in jQuery,
11:18we have the $(document).ready function.
11:22This does a very similar thing, meaning that the code we put inside here will be
11:27executed when the DOM is fully loaded, but if we needed to, we could actually
11:31call that same thing multiple times, and we wouldn't have to worry about the last
11:36one overriding the first one.
11:38In this case, I am calling it twice.
11:40Once I will change the content of this page ID to "The DOM is fully loaded,"
11:45and then in the next one, I am going to set colors of h1 to red.
11:48We refresh that page, and we can see that both of those are being applied.
11:53Now this is just a taste, a quick intro.
11:56jQuery gets a lot deeper than this, of course.
11:58So check out the documentation on jquery.com or take a look at one of several
12:03jQuery courses we have here at lynda.com.
Collapse this transcript
Using a content distribution network to deliver JavaScript files
00:00We've seen that it's simple to download jQuery so that you have a copy of the
00:04file on your site to send to your users.
00:07But there is a better way:
00:08let somebody else do it.
00:10Several companies, including Google and Microsoft, allow you to link to jQuery,
00:14and some other common libraries, and get that file directly from their servers.
00:20And they don't just have one server but typically a bunch of geographically
00:25distributed servers with load balancing and failover, all in a Content
00:29Distribution Network, or CDN, so it's almost always faster for the user to get it
00:34from one of their servers than from your server.
00:38And using this is all free, and it's super easy.
00:43All you do is in your HTML you find your script tag where you're linking to the
00:47local copy of the file and you just change it to use, say, Google's link to it.
00:52You're not changing anything else about your own site.
00:55You're still hosting your site and your pages the same way you ever did, and
01:00that's it; you're done.
01:02If you ever wanted a reason to stop doing this, you would just change this link back.
01:06Now, more and more sites, even very large ones, are using Google's CDN to deliver
01:11JavaScript library files instead of hosting it themselves, and there is really
01:15a few benefits here.
01:17First is the speed idea. Google takes care on delivering that file.
01:20They have a fantastic network and they're very reliable, and any random user is
01:25closer to a Google server than to your server.
01:28So you don't have any bandwidth concerns.
01:30Okay, jQuery and the like, they are small files, but that bandwidth can still add up.
01:35A three, a real benefit here is when loading a page, browsers limit the
01:41amount of simultaneous requests by domain, so by spreading your assets across
01:46domains, that can help, because one last request to your server for JavaScript
01:51means the browser can be making requests to your server for other assets, like CSS and images.
01:57And as more and more sites use Google's CDN that file becomes effectively
02:03shared across sites because of it being cached in a user's web browser.
02:08The idea is if your user visit, say, site A, and they retrieve some HTML that's
02:15linking to a JavaScript file stored on a Content Delivery Network, they'll be
02:20delivered that jQuery file, or whatever it is, from that set path, and that path is
02:26remembered and cached by the browser.
02:29So if that user then goes to another site and retrieves some HTML and CSS that's
02:34also using that same CDN and that same path, the browser will realize, hey, I've
02:40already got a copy of that jQuery file. I don't need to download it at all.
02:45So I've talked about jQuery here, as it's the most common, but if you want to
02:48know what other libraries are available, we'll get in more details, go to
02:52code.google.com/apis/libraries.
03:00Or if you don't remember that, just search for Google CDN.
03:03Now these are the current ones that are available.
03:06We've got Chrome Frame, Dojo, jQuery, MooTools, Prototype, script.aculo.us, and
03:12clicking any of them will give you a bit more information about how you get hold of them.
03:17Now when you browse through this developer's guide you'll find a lot of content
03:21about signing up for a Google API key and using their loader JavaScript.
03:26You really don't need to do this. The most direct way is just to come on down to
03:30the library that you're looking for and find the path to it.
03:33Now one more thing: you'll see that Google makes this path available as https here.
03:39That's where it showing up in this list. In fact, it is available as both
03:42http and https paths.
03:46The main reason it needs to be available as an https address is so you can use
03:50it from an encrypted page without the browser complaining that you're using an
03:55unencrypted asset on that page.
03:57There really is no other benefit to encrypting jQuery; everybody knows what it is.
04:03But if your site needs to link to jQuery from pages at a variety of http and
04:08https addresses, one shortcut is that in your link to that file you actually
04:14just remove the protocol from the link, so you remove http: or https:
04:20and just have the two forward slashes.
04:22It looks a little strange, but that will just use whatever protocol the
04:26current page is using.
04:27And that's all there is to it. The only place I wouldn't use Google's CDN is if I
04:33was developing a purely internal intranet site where my users are literally in
04:38the same building as the web server.
04:41But otherwise, I highly recommend a CDN as your default way of linking to a
04:45library like jQuery.
04:46There really are no downsides here.
Collapse this transcript
12. JavaScript and HTML5
JavaScript in HTML5
00:01If you build web pages, you probably know HTML5 is the newest version of HTML,
00:06and it is the way the web world is moving.
00:08It adds great new features to web sites, many of which were previously only
00:12available by using external plug-ins like Flash or Java, but this will make them
00:16part of the regular web, standardized across all platforms across all devices.
00:22And we're big fans of the HTML5 here at lynda.com, but if you haven't done much
00:26with it yet, it's often a little confusing to approach,
00:29particularly because HTML5 is talked about along with other technologies, like
00:34CSS3 and JavaScript.
00:36And these aren't part of HTML5, but they do typically come along for the ride.
00:41And that is an important distinction.
00:43HTML5 is not changing this arrangement.
00:46It's HTML5 for your markup, CSS3 for your presentation, and JavaScript for your behavior.
00:52Now if you remember our discussion of ECMAScript earlier in the course and that
00:57what we're doing in this course is ECMAScript 3, you might think, "Well, does
01:01HTML5 mean I must have an ECMAScript 5?"
01:04Unfortunately, it's not quite that simple, and here is really the first
01:08problem with the picture. HTML5 is not finished yet.
01:12The specification is still a work in progress, but that does not mean you should
01:17be holding off thinking, "Well, I'll wait and see if it gets implemented."
01:21HTML5 is happening.
01:23We know what's going to be in it.
01:24There are pieces of it already implemented in the latest browsers, and there are
01:29things we can be doing right now to work with it.
01:32So what are these main features?
01:35HTML5 brings new tags, new elements, new abilities, and the main areas are
01:40better support for video and audio built into HTML itself, so we don't have to
01:46use Flash plug-ins, for example.
01:48There is a new element called Canvas that will allow us to draw on the screen directly.
01:55There is offline storage support, so web sites can actually store a significant
02:01amount of data, meaning they can be used without a connection.
02:04There are a whole lot of new form elements for building better forms.
02:09There is drag-and-drop support, built-in abilities to drag and drop items, not
02:14only within your own pages, but actually between web sites.
02:16There is Geolocation, understanding of latitude and longitude built into
02:22the language and local storage, being able to store more data than just simple cookies.
02:27And there are new JavaScript APIs.
02:30What that means is it kind of makes sense that there will be new objects and
02:34methods in JavaScript, if we want to write code that works with these features.
02:39But here's an important thing.
02:40These features are being implemented into new browsers piece by piece, not as one thing.
02:47Firefox 4 has core support for all the main HTML5 features, but if you've had to
02:52support Firefox 3, you'd lose most of them.
02:54Similarly, Internet Explorer 9 has support for just about everything, but if you
03:00have to go back to Internet Explorer 8, you're going to lose quite a lot of
03:04this, and it's the same story with the other browsers.
03:07Now if you haven't come across this site before, this is caniuse.com, and it
03:12allows you to break down features of HTML5 and CSS3 that are available in
03:18the different browsers,
03:20some of which have very good support, but as you get further on you'll find
03:24certain ones missing, and then the general scorecard for how well the different
03:29browsers are doing for each of those features.
03:31But we're really focused on JavaScript here, and while this course, as we've
03:36mentioned, concentrates on the core of ECMAScript 3, there are a couple of new
03:40things that you should know about that are coming along with HTML5.
03:44In addition to the regular getElementByID and getElementsByTagName that we know
03:49about, we now have the much-requested getElementsByClassName, which returns all
03:55elements that match that class.
03:56You can even tell it to find multiple classes separated by spaces.
04:01Most libraries like jQuery and Prototype have implemented their own version
04:05of this for years, but it's great to have it finally natively supported in the language.
04:10But this is really the only general-purpose new method that I would associate
04:15with HTML5, and it's not available in Internet Explorer 8 and before,
04:20so if need that functionality in earlier browsers, look at using jQuery or
04:25another Library, because most of the new JavaScript abilities in the most recent
04:30browsers are just support for those new HTML5 features in those browsers.
04:36Here's an example of that.
04:37So in HTML5 there is a new video tag in the markup, and while this does work
04:42quite well on its own, if you grab the video element object using, say,
04:47getElementByID, you can then call methods of it, like .play and .pause, and set
04:54properties of it like the currentTime and do that all through JavaScript.
04:58And the object also has events, so we can choose to listen out for say the ended event.
05:04Now you might recognize that here I'm using the addEventListener format for
05:09working with events.
05:10This is the one that I talked about earlier in the course that I was avoiding
05:14because of cross-browser differences.
05:16But here, I can pretty much assume that if I have a browser that supports the
05:20video tag, it certainly supports the addEventListener method.
05:25And there are other events, such as play and pause, that we can react to.
05:29Now for more information about video, take a look at our course, HTML5:
05:33Video and Audio in Depth.
05:35Similarly, HTML5 brings a lot of storage options along with it that we can
05:40target in JavaScript, from simple localStorage where you just pick a name and
05:46start storing and retrieving simple values all the way to full offline support
05:51allowing your site to be used as an application without even requiring current
05:55network connection. And then there is Web SQL and something called IndexedDB,
06:00really adding substantial local storage abilities to the web.
06:05And if you're interested in more about this, check out our course on HTML5:
06:09Local Storage and Offline Applications in Depth.
06:13Now, HTML5 does have a new JavaScript feature called Web Workers.
06:17We'll be able to load JavaScript and make it run in the background, regardless
06:21of what else is going on in your page.
06:23This is something that most other languages can do, usually under the term
06:26multithreading, but JavaScript has never been able to do.
06:30You can create a new Worker object and point it to a separate file of JavaScript.
06:35Now, the Worker object can't directly affect the DOM, so you have to allow it to
06:40generate events and send them back, reacting to a message event from the Worker
06:46the same way you might react to a click event from the user.
06:51And from your page you can send messages to kick off certain functions in the Worker itself.
06:57Now Web Workers aren't supported in Internet Explorer yet, but are available in
07:01Chrome, Safari, Firefox, and Opera.
07:04And while there's obviously more to it, you can tell that HTML5 is bringing
07:08some interesting stuff
07:09that's going to impact us as JavaScript developers.
07:12So the question is, what if you want to use these features?
07:15Well, you can't just ask, does this particular browser support HTML5?
07:21That's the wrong question, because as you've seen, HTML5 is really not one thing.
07:25It's a collection of features and abilities all wrapped up and given this name HTML5.
07:31And your responsibility as a JavaScript developer is to be aware of the new
07:35features that HTML5 brings, figure out if they meet a need for you, and then
07:39write any code to deal with that particular feature, and perhaps to deal with
07:44that feature not existing in an older browser.
07:46So if you want to be an early adopter with HTML5, you will be interested in
07:51cross-browser differences.
07:54Now, if you wrote any JavaScript more than a few years ago, the idea of detecting
07:58differences between browsers might seem like a throwback to the bad old days of
08:03trying to detect whether the user was on Netscape or IE 4.
08:07This is not the same thing here that we're talking about.
08:10We're not remotely interested in browser detection, but we are interested
08:16in feature detection--big difference.
08:18You do not want to be worried about writing code to detect whether the user has
08:22Chrome version 12.1 on a Mac or Firefox 3 on a PC, but we might want to ask,
08:28does the current browser support the new video functionality in HTML5?
08:32If so, I'll use it; if not, I'll do something else.
08:35It's the specific features we care about.
08:38Feature detection in JavaScript is quite simple.
08:41You treat the feature as an object and ask if it exists. Well, how?
08:45Well, here I'm writing a little bit of code to ask if the new
08:49getElementsByClassName method exists in the current browser.
08:53And the way that I just do it is just name it inside an if statement.
08:57If it exists, this will be regarded as true.
09:00Now very important, notice that here I'm not calling the getElementsByClassName.
09:04I'm not using the opening and closing parentheses and passing any parameters;
09:08I'm just using the name of it inside our if condition.
09:12And you can do this with any of the future-facing objects.
09:15First check if it exist, and if it does, use it; if doesn't, ignore it or
09:19fall back to some backwards-compatible way.
09:21For example, if HTML5 video doesn't exist, we can generate some elements to
09:25include a Flash Player.
09:27And next up, what I'm going to cover is a very simple way to detect all the
09:32HTML5 features that might or might not be available in a browser.
Collapse this transcript
Using Modernizr
00:00This is web development, so we'll be working with browsers with different feature
00:04sets for a long time to come.
00:06And though we can rank most ECMAScript 3 without caring much about
00:09browser differences,
00:10if you're going to be an early adopter of HTML5 features, it really does become
00:15an issue, and there's a great library you should take a look at that will help you
00:18build those HTML5-focused apps while staying aware of backwards compatibility.
00:23It's called Modernizr. It allows you to do easy feature detection of both HTML5 and CSS3 features.
00:31Kind of like working with JQuery or any other library, you can simply download a
00:35copy it from modernizr.com and link to it on your web page.
00:40Now it's suggested that you actually put this file linked to in the head of
00:45your document, as the code here needs to run immediately, actually before the body tag loads.
00:50It's very lightweight, so that shouldn't be an issue.
00:53Now as soon as it runs, what you'll have is a new JavaScript object called
00:58modernizr, with over 40 properties that are just Boolean values to say whether
01:04a particular HTML5 feature is supported.
01:07So modernizr.video, modernizr.audio, modernizr.canvas, modernizr.draganddrop.
01:14Run it on one browser, you may get a whole bunch of true results; and run it on a
01:19different browser, you made a couple of true and a lot of false ones.
01:23What we can then do is just write code that asks if modernizr.video, then yes
01:29we have support for it.
01:31We can generate some HTML5 video elements.
01:34If that's false then perhaps we can generate some flash video elements instead.
01:39This will be the concept of progressive enhancement.
01:42If the user has that feature, we will enhance the site with it;
01:45if not, we might do nothing, or we might fall back to an alternate method, but
01:50what won't do is give them something that's broken.
01:55If you download the full version of Modernizr from modernizr.com, it allows you
02:00to check for every feature in HTML5 and CSS3, and it would be very unusual for
02:05me to actually need this.
02:07So once I know exactly the features that I'm looking for, I can go back and go
02:11to their Production section where I can just configure a custom build and
02:16generate a smaller version with the exact checks that I need. So, for example,
02:20if I am only interested in drag-and-drop and HTML5 audio support, I can then
02:25tell it to generate that file, and I just get the much smaller piece of code here
02:31that I can use to say true or false for just those particular features.
02:35Modernizr does not, of course, give you these abilities if they're missing;
02:40it's simply a very straightforward way to see if they're supported.
02:44If you do want to get into more advanced uses, it can help you load in what I
02:48preferred to shims and polyfills, which are ways of detecting a missing feature
02:54and then trying to load in some alternate code to emulate that feature, but that
02:59is certainly beyond the scope of this course.
Collapse this transcript
Using Strict Mode
00:00This next subject isn't strictly part of HTML5, but it is a forward-looking
00:05piece of JavaScript, so it belongs in the same discussion.
00:08You may come across references to something called Strict mode in JavaScript,
00:12particularly if you use code checkers like JSLint.
00:15Now, Strict mode is part of ECMAScript 5, but even though we're focused on
00:21ECMAScript 3 in this course, we might well be interested in it for our own code.
00:27It's a way to volunteer, to have your JavaScript to be held to higher standards
00:32than regular JavaScript, which has we've seen, will let you be sloppy.
00:36If you turn on Strict mode, for example, you must declare variables before you use them.
00:42If you fail to do so, that's an actual error. Your script will break.
00:46Strict mode will also cause an error if you define a function with multiple
00:50parameters with the same name.
00:52There are several more things it will complain about, a lot of them more advanced.
00:57And to volunteer for Strict mode you simply do this.
01:00At the top of any file of JavaScript you'd put the words "use strict" inside
01:07double quotes, semicolon as its own line.
01:11Adding it up here means I'm saying turn on Strict mode for this entire file.
01:16You'd also add it as the first line of any function if you want to just do it
01:20function by function.
01:21But here's the thing, only certain browsers support Strict mode.
01:25Well, that's okay because browsers that don't understand it will simply look at
01:29this line, figure out it's a string literal by itself, and just ignore it.
01:33Browsers that do understand Strict mode, for example Firefox 4, will then be
01:38extra picky about your code.
01:41So to prove that this works, I'm actually first going to just remove this, so we
01:45can run this code without Strict mode, and it's a very simple piece of code here
01:51that's just going to output the term "Hello world" here to this area of my HTML.
01:57And as I can see, Firebug isn't giving me any errors here.
02:01But if I jump back into the code and I turn on use strict mode, save that again,
02:08go back over into Firefox, and refresh this page,
02:13instantly we have a problem.
02:15It starts off here saying, "property name samename appears more than once
02:19in an object literal."
02:20And bear in mind this is not just a diagnostic message; the script has broken.
02:25A moment ago it was actually changing the contents of this div and now it is not.
02:30So this line here where I am creating a new object and I've given it two
02:34properties with the same name, that was forgivable in regular JavaScript.
02:39It is not forgivable in Strict mode.
02:44So I'll fix that one, go back refresh it again.
02:48Now it's giving me another problem, "duplicate formal argument A." It looks like
02:51in this function I've declared three parameters, but two of them have the same
02:55name, and that's not going to do at all.
02:56So I come back over here. Again, regular JavaScript would let me get away with that.
03:02It might have caused a logic problem, but it would still have attempted to work.
03:07Refresh it again, "assignment to undeclared variable foo," foo = "Hello world."
03:13That's because I'm not using var at the top here.
03:16So save that one, go back, test it again, and then finally, we're working correctly.
03:23Now I'm a fan of Strict mode, so I actually tend to turn it on, but there are
03:29two things to be careful of.
03:31One, because it's common to combine multiple JavaScript files into one when
03:36you're trying to optimize performance, make sure that if you're putting "use
03:39strict" at the top of some of your files, you're not then mixing them up with
03:43some other files that don't use Strict.
03:46And bear in mind you can use Strict mode on a per-function basis.
03:49And if you know you're going to be combining multiple files together, some which
03:53use Strict mode and some which don't,
03:55you can combine the files with a blank function wrapper, which might look a
04:00little odd, but you do something like this,
04:02where I'm opening a parentheses in a function body at the top and I'm going to
04:08close it using the following format at the bottom, and then "use strict"
04:15effectively is the first line of this particular function.
04:19This is actually what JSLint currently recommends as a way of doing it, but I
04:23think it's kind of clunky, but it's an option.
04:26But secondly, and more importantly, if you're going to be working with Strict mode,
04:34don't turn it on and then only check your code in browsers that don't support it,
04:39because bear in mind even using Strict mode, or turning it on, your code may
04:43still work in non-strict browsers and only break in Strict mode in a supported
04:49browser, so make sure you check it across multiple different browsers with the
04:54different capabilities.
Collapse this transcript
13. Advanced JavaScript Features
Knowing the JavaScript to avoid
00:00JavaScript is not only the most popular programming language in the world,
00:04it's one of the most badly written and because of its history,
00:08there's a lot of bad JavaScript out there on the web. And there are several
00:12things you're likely to see when reading JavaScript that I specifically chose
00:16not to include in this course.
00:18Now at this point, I'm going to tell you a few of them, so you can recognize them
00:22and make your own choice about whether to look deeper at them or not.
00:25And the first one is document.write.
00:29This is very commonly seen in early JavaScript tutorials.
00:33It lets you write a string directly to the current page, and as you can see from
00:38this example, you can even include HTML tags inside it.
00:41Let me show you a basic example here.
00:46So I've got a very straightforward HTML page and instead of making a
00:50separate JavaScript file, I've just got two document.write calls inside a script tag here.
00:59If I run this page, I'll see that this is outputting some text directly into
01:05the body of the page, whereas the previous text is just here inside a h1 and the paragraph tag.
01:13And it doesn't look so bad,
01:16but there are a few issues with this.
01:17See document.write doesn't work in XHTML,
01:20it doesn't understand the DOM properly, and it just spits out stuff
01:24wherever it's placed.
01:25It's a clunky inflexible way of doing anything with a page.
01:29And the most substantial reason that you don't want to get used to it is because
01:33you can only use it when the page is initially loading.
01:37If, for example, I decide to have a function and put document right inside that
01:44function and then I'm going to just call that function a couple of seconds
01:49after the page has loaded,
01:51let's see what happens. So I save that.
01:54I flip over to Firefox where we have it.
01:58I refresh this page and two seconds later, the document.write destroys the
02:04original page, because it will only work as the page is being created for the first time.
02:09Run it anytime after the page is loaded,
02:11it will erase the contents of the document, so much better to use innerHTML,
02:16or better still, to work with creating and manipulating the individual DOM
02:20elements and text nodes.
02:23Next step is if you ever see code that looks something like this,
02:28browser-sniffing code. You're reading something that seems to be detecting
02:33Netscape or Microsoft Internet Explorer or a particular platform.
02:37This is really old-school stuff.
02:39Browser sniffing, it used to be necessary, but it hasn't been for several
02:43years, and it's usually a dead giveaway that what you're looking at is very old
02:47code, or it's written by someone who hasn't brushed up their JavaScript skills in way too long.
02:52Any code that seems to be detecting an actual browser or an actual platform
02:57should be looked on with great skepticism. While there might be a very
03:01occasional edge case where you want to do something with a particular browser,
03:06in general, any detection we should do is detecting features, not browsers, and
03:12that's much simpler than working with the navigator.userAgent properties.
03:17Next step is the EVAL function.
03:19EVAL is a powerful little function that can take an expression and execute it as code.
03:24That sounds a little weird, so let me show you what I mean.
03:27Let's say I create a variable a that's a string and it contains kind of half a
03:33statement here, and variable b contains hello, and variable c contains a closing
03:38single quote and closing parentheses.
03:40What we can actually do is use EVAL and then we could combine those three
03:45variables together into one long string. And if I pass it to EVAL function, EVAL
03:51will actually cause that to be executed as if it was code.
03:54Now the issue is there are almost always better ways to do it than EVAL.
04:00This is really ugly.
04:01It's hard to figure out what's going on. It's inefficient.
04:04It can lead to security problems, because you're executing code that's stored in
04:08variables and if you're reading one of those variables from the outside world,
04:11say the contents of a form field, it can effectively inject code you didn't
04:16write into your JavaScript.
04:18It's generally agreed upon that EVAL is a bad thing, so you might see it, but don't do it.
04:26And the fourth thing I wanted to mention is what's called a pseudo-protocol.
04:29This is very common to see inside HTML.
04:32It's a way of making a link or a button directly call a function.
04:37So in a regular HTML anchor tag, instead of having an a href equal to the address
04:43of a web page using HTTP, we have javascript:
04:47and then say the name of a function.
04:50This is called a pseudo-protocol, because usually what you'd be doing here
04:54is linking to http: or https:
04:56and those are real Internet protocols; javascript: is not.
05:02It's just a way of telling the browser to call a JavaScript function here
05:06instead of going to an actual address.
05:07Okay, it looks pretty easy, but what's the problem?
05:10Well, one, you're mixing your HTML with your script, not a good a thing in
05:14principle; and two, if JavaScript is disabled, this is useless.
05:19You have a link that does nothing.
05:20Now there is a similar format that's slightly better, where you use the name of the event.
05:27So in this case I do actually have an href here that's pointing to an actual
05:31page, an actual address, and then I have onclick=, in this case someFunction; return false.
05:38This is preferable to the pseudo-protocol.
05:41Here, at least I have treated this link as the link it's meant to be, with a real
05:45address, and I've added the onclick handler as a separate attribute.
05:50Now what you often see here is the statement "return false" and this is here to
05:54stop the default behavior of this link, which would be to follow the actual link here.
06:00So in this case, if JavaScript is enabled, we will run the JavaScript
06:04function called someFunction and if not, we would call the JavaScript HTML
06:10link and follow that link.
06:11And I'm not a big fan of this method either, and I much prefer leaving my HTML as
06:17pure content as possible and adding event handlers directly inside my code,
06:22which is why, all along in this course,
06:24we've attempted to use JavaScript that when it runs adds functionality to an
06:29existing page that already works, since, again, this is the concept of
06:33progressive enhancement.
Collapse this transcript
Introduction to regular expressions
00:00JavaScript, like many programming languages, if not all of them these days, has
00:05regular expressions built into the language.
00:07Now, regular expressions are odd-looking sequences of characters that describe
00:12and can match patterns and strings.
00:15They let you verify that a credit card number has the right amount of digits,
00:18or that an email address, or URL matches a basic pattern, or that a password
00:24has a mixture of uppercase and lowercase letters, or just define certain words in a larger string.
00:30Now nobody finds regular expressions pleasant to begin with, but they are very
00:33useful, and there is always two parts to them:
00:36first you create the regular expression that describes the pattern that you are
00:40looking for, and then you apply it to something else to see if it matches.
00:44So step one, we describe the regular expression.
00:47We can create a variable in JavaScript.
00:50I've created one called myRE for my regular expression and set it equal to /hello/.
00:57This is almost like creating a string variable except we don't use quotes but
01:02forward slashes to mark the beginning and the end.
01:05Now, this is actually a shortcut in JavaScript for the longer version, which
01:09we could use the new keyword, new RegExp, or regular expression object and pass in hello.
01:16These both would create the same variable.
01:19It's the same way that we can create a new array object or use square
01:22brackets as a shortcut,
01:24we can make a new regular expression object or use the forward slashes as a shortcut.
01:28Now this is about as simple a pattern as you can get.
01:32It's just going to look for the word hello to exist somewhere in a string to
01:36be matched against.
01:38So I can then create a new string, in this case call it myString, and what I am
01:43going to do is call the test method of my regular expression against my string.
01:50So if myRE.test, pass myString in, does that word hello occur? Yes, it does.
01:55We'll pop up an alert.
01:56Now this is case sensitive.
01:59Calling test will just return true or false.
02:02If you called search instead, you would actually return the position of the first match.
02:07Now, a complex pattern than just single words are created by using special
02:14characters, so as an example if I created a regular expression variable with
02:20the carrot symbol, this would denote the start of the word or the string that
02:25we are matching it again.
02:26So hello would have to appear right at the start of the string.
02:31On the flip side, hello with a dollar sign at the end means hello would have to
02:34appear at the end of the string.
02:36And we can get even more specific.
02:40If I use a plus sign somewhere in the regular expression, that means the previous
02:45character, in this case L, has to appear once or more, which in this case would
02:50match for hello with one L, hello with two Ls or hello with a dozen or 500 Ls.
02:57If I instead used an asterisk, that would be zero or more times, so the previous
03:02character L would have to be there zero or more, which means it would also match
03:06on h-e-o, so no L at all. And then we can also use a question mark, which means
03:12just zero or one, so h-e-o would match, h-e-l-o would match, but any more Ls than
03:18that would not match.
03:22If I use the pipe, it means either/or.
03:25In this case, it'd be true if the string contained either hello or goodbye.
03:32If I use the point here, it means any character, which would much a whole bunch
03:36of different things.
03:37Now you will also see the backslash used a lot with regular expressions.
03:43So \w used as one little piece here means that this must be an alphanumeric
03:49character or an underscore.
03:50\b means a word boundary, like a space or a new line, which means here that hello
03:58would have to appear after a space or after a new line as a word by itself and
04:03not as part of another word.
04:05And very often you'll also see the square brackets being used to denote a range
04:10of characters to match on.
04:12So in this case, I've got c-r-n-l-d inside square brackets. That means any of
04:17those letters followed by o-p-e will be regarded as true, but if I have a
04:23different letter, it will not.
04:25Now as you're probably beginning to tell, there's a lot of these things, and there
04:31is way more than I can show you here.
04:33What we start to do is describe more complex patterns by starting to string them together.
04:40So as an example, here is one that would check for a valid format for a US ZIP
04:45code with an optional four-digit extension.
04:49We are surrounding it with the forward slashes at the start and end. Then we are
04:53using the carrot at the start to denote the start of the string and saying what
04:57characters allowed, how many characters there can be, and then the question marks
05:01to denote whether things are optional or not.
05:03Now, bear in mind you're likely to begin by finding examples of these online.
05:09If you're looking for a regular expression to match a credit card number format
05:13or a date or a password, there is really no reason you should be writing it
05:16yourself from scratch.
05:17Now, oftentimes the best regular expression is a matter of some
05:20considerable debate.
05:22People have been arguing for many years on what the so-called ideal regular
05:27expression for an email address would be.
05:29Now, here is actually very simple one.
05:31What this is saying is that the first part of the line begins with a carrot and
05:35then after than we can have multiple letters, digits, periods, dashes and
05:40underscores. Then the @ must exist and then more of these matches where we
05:46can't use the special characters, then at least one, and then it must end with
05:52the top-level domain, which can be two to four letters like.com.net.org or a
05:58country code like UK.
06:00But here's the thing, email regular expressions are notoriously difficult, and
06:05this one actually isn't correct.
06:06It won't allow long top-level domains like.museum, which might be rare, but
06:11certainly does exist.
06:12And it doesn't allow plus signs in the email, which can be used by some mail systems.
06:17In fact, the range of permissible email addresses is more complex than you might
06:21think, and if you include non-Western character sets, you should get into more
06:26complex regular expressions that are dozens, or even hundreds, of lines long.
06:30There really is no perfect regular expression for validating email.
06:33There is just a variety of ones that are good enough, and this is worth bearing
06:38in mind with regular expressions.
06:40There is a lot of knowledge out there.
06:42Right now, what you need to understand is what they are and how they used.
06:46Regular expression syntax is not something you need to memorize just yet, if
06:50you've never come across them before.
06:52They are a tool, and there are something to be used when you need them.
Collapse this transcript
Working with AJAX
00:00One of the reasons for the resurgence of JavaScript in recent years is the
00:04enormous popularity of what's come to be known as AJAX.
00:07Now, AJAX sounds like a separate technology or a language; it isn't.
00:12It's just a useful buzzword to describe a cool technique we can do with JavaScript.
00:17While it officially stands for Asynchronous JavaScript and XML, well, it's
00:22really more to do with AJAX being a good acronym than anything else, because it
00:26doesn't even require XML.
00:28As far as we're concerned, AJAX is JavaScript.
00:32It's just a very specific use of it.
00:34What it means is that after a web page has opened in the user's browser, we
00:41can have JavaScript behind the scenes communicate back to the server, even
00:46pass and retrieve data, and update parts of the page without the entire page
00:51itself needing to reload.
00:56A simple example, if you've used, for example, Google, and started typing, and
01:02found it able to start to fill out the information that it thinks you're looking
01:06for and actually update the page as you're typing, this is AJAX going on.
01:13As I'm typing, JavaScript is passing these characters to the web server, which
01:17is then returning the most likely results as I type and updating the page
01:21without me actually refreshing the page at all.
01:24If you use an online map, the ability to scroll into places, or to zoom in and
01:29as I zoom in start seeing more and more explicit data is the same idea, that this
01:34is being fetched from the server as I'm using the Zoom button.
01:38Now, in a lot of cases this is almost transparent if I'm working with it slowly,
01:43but if I start to drag quite quickly, you'll often see it hurrying up to try and
01:47fill in that data for me.
01:53Either way, it's certainly usable.
01:54So this technique, this AJAX ability, lets you make more responsive sites,
01:59sites that can behave like real applications. And for things like search,
02:03autocomplete, and maps, being able to load data on the fly actually makes these sites possible.
02:08There is no way we could load all the data upfront.
02:12AJAX builds on all these skills we've been working with so far: understanding
02:15basic JavaScript, grabbing and manipulating DOM elements.
02:19There are two new things we need to be able to do.
02:21One is, from JavaScript, create an object that will call the server.
02:26We're creating a request here.
02:29And two, then is a very separate part, is let the server pass information to us
02:35to deal with any response.
02:37Now, these are done as two distinct steps rather than say one function call,
02:41because we don't know how long it's going to be between the request and getting
02:45the response, and we don't want to hang the page while we wait.
02:48This is the asynchronous part of AJAX.
02:51So how do we do this?
02:52Well, to do it we work with a new object, the XMLHttpRequest object.
02:58This is the middleman between our page loaded in the browser and the server
03:03side, any communication we want to do.
03:05But unfortunately, it's actually one of those objects with a cross-browser
03:09difference, so I can't just write a line of code like this that creates it.
03:13I first have to see if it exists.
03:17So what I do is something more like this.
03:19I'll just define the variable, and then I'm going to do a feature check,
03:23ask if certain objects exist on this browser.
03:26In this case, what I'm asking is if (window.XMLHttpRequest). That doesn't do
03:32anything except ask, is there an object of this name?
03:35If there is, I know I'm on Firefox or Safari, or a browser like that, and I can
03:39then go ahead and create a new XMLHttpRequest.
03:44If that returns false, I'll then go on and check, well, do you have
03:48window.ActiveXObject?
03:49If that's true then I'm running on Internet Explorer, and I will create it as
03:54the Microsoft.XMLHTTP object done this way.
03:58This is one of those areas where you can't really blame Microsoft for being a
04:02little different, because they actually did invent this object in the first
04:06place. So they're not just trying to do a different version of it;
04:08they just have their own specific reasons for creating it.
04:11Now, what I have to do after this is I haven't yet said, what am I calling?
04:16Where on the server am I reaching to?
04:18Have I executed this request or not?
04:20So I do need to go ahead and configure and send it, but not yet, because I first
04:26have to tell it what to do when a response comes in.
04:29That's the second part of this.
04:31Now, that request object, when we execute it, will start to kick off events the
04:37same way as a lot of things kick off events.
04:39The one we're really interested in will be the onreadystatechange event.
04:45And the same way as dealing with say a userClick event or a windowLoad event,
04:50we say, okay, when this event is occurring on that request object, I'm going to
04:54call, in this case, an anonymous function, which right now will just output a message to console.log.
05:00However, as we'll see, this event is actually quite chatty, and the request will
05:04cause this event to be called multiple times before we're completely finished
05:08with the entire communication request.
05:11I'll get into that in just a moment.
05:13But after I've been prepared to accept this response, after I've created this
05:17event handler, then I can configure and send it.
05:20I tell it where the request is going.
05:22In this case, I say I am using a GET rather than a POST.
05:26I am going to call the address, in this case, mysite.com/somedata.php.
05:33The last argument here of true means yes, this is asynchronous, so as soon as we
05:37do it, we're going to go ahead and execute any other JavaScript code, and we're
05:42just going to allow the browser itself to handle any response--
05:45we're not going to wait for it. And then we send it.
05:49I am passing Null here, but if I had some parameters to send, I could do that too.
05:54So let's see a simple example in code.
05:58I have about as straightforward an HTML page as I can have here.
06:02I've got one div called mainContent with "This is an AJAX Example," and in my
06:08script file that I'm linking to, I have some simple boilerplate code for
06:12creating this AJAX request.
06:15So on Line 4, I defined a variable called myRequest. On Line 7 I am going to
06:21ask, if the XMLHttpRequest object exists.
06:25If so, we're in Firefox or Safari, I'll go ahead and create it.
06:28If not, we're probably in IE, so I'll go ahead and create it the different way.
06:32Either way, by the time I get to Line 14, I should have an object.
06:35I am going to create an event handler for our request, which in this case we'll
06:39just call console.log, and say, "We were called!"
06:43Line 19, now I have to configure that request. Where is it going?
06:47In this case I am going to say to a GET, and I've just given it the address of
06:51simple.txt, which is effectively going to treat it as a relative link here.
06:55I wanted to do it simply so that I didn't have to work with creating up server-
06:59side scripts, all that kind of thing.
07:01I do have a file that's existing at the same location as my HTML page and
07:06my JavaScript file.
07:07It's just called simple.txt and it says, "This is the contents of a simple text file."
07:13So that's what we're after.
07:15And then we're going to send the request.
07:17Now, after I execute this code if I did have more JavaScript code, it would just
07:22go on and execute any subsequent JavaScript.
07:26We're not waiting for the request to come back.
07:29That's why we set up the event handler. Because whether that request takes 10
07:34milliseconds or 10 seconds, we don't want to block,
07:38meaning we don't want to hang the page. So we just go ahead, and when it calls
07:42this back, it will jump back here into this anonymous function.
07:46So let's see if this works.
07:47I'm going to jump over and just execute this code, open it up in Firefox.
07:55Now, I do have my console open here, and I can actually say that I got that
08:00console.log message that we were called five times, which is a little strange.
08:05Well no, it's not, really.
08:07The thing is is that this onreadystatechange event actually gets called multiple
08:12times, and every time it's called it's at a different stage of the request and
08:17response, and it passes in a little piece of information.
08:21I am going to write that out, so you see what it looks like.
08:23I am going to say console.log. I have a property of the request
08:33object called readyState.
08:35So if I save this, go back over and refresh it again, I can see that I get
08:39called several times with a different state: 1, 2, 3, and 4;
08:43in fact, 4 is the one that I am interested in.
08:45When there is a ready state of 4, I then know that I've gotten a response back
08:50from the server from whatever I was asking for.
08:56So what I am going to do is just put in a little bit of code here.
08:58I am going to be starting off with an if statement.
09:01If (myRequest.readyState === 4) meaning I know I've got a response back, then I
09:07am just going to call a few DOM methods here.
09:10First, I am going to create a new paragraph element and call it p. Then I am
09:15going to create a new TextNode.
09:16Now, here's the only important bit about this.
09:19We've seen everything except this.
09:22Once that response has been received, I will have a property of the request
09:26object called responseText, and that's going to be whatever I got back from that call.
09:32So we create the element.
09:33We create a TextNode with that content in it.
09:36I then add the TextNode to the paragraph.
09:38I then add the paragraph to the DOM tree, to the mainContent div.
09:44So save this file, jump back over into the browser, and what I am hoping for is
09:49when I refresh this I will see the page itself updating that content. There we go!
09:53This is the contents of a simple text file.
09:57Now, obviously because all my files are running locally, what I am not seeing is
10:01perhaps the slight delay that I might have in updating this page, but this is
10:06still proving the point.
10:07Yes, it's a simple example here, but the entire process of doing this in a
10:11production site is the same.
10:13We're creating a request, we're setting up a handler to wait for any response,
10:18and then we're firing the request off.
10:21Now, as with other areas where there are cross-browser differences, when I am
10:25doing anything substantial with AJAX, I am a fan of using a library like jQuery
10:29which provides helper functions, so you don't have to worry about writing the
10:34cross-browser check, because it can get a little more complex with older
10:38browsers, for example.
10:39So take a look at that if that's an area that you're interested in.
Collapse this transcript
Working with objects and prototypes
00:00In this course, we have covered creating date objects.
00:04We have covered creating array objects and regular expressions, and these are all
00:08built-in and predefined objects in JavaScript.
00:11And we've even talked about how to make our own simple objects, which we start
00:15off by just creating new variables that are wrapping several other variables
00:20together under one name.
00:21But we can go deeper with this idea, and for those of you who are interested in
00:25going deeper, particularly if you're coming from another object-oriented language,
00:30here's a quick introduction to the concept of a prototype in JavaScript.
00:35First, what can be a source of confusion is that there is a popular JavaScript
00:39library called Prototype, but that's not what I am talking about here.
00:43I'm talking about the prototype built-in language future of JavaScript which
00:47will help us create more formalized objects.
00:51So what is the problem anyway?
00:53Well, a quick recap.
00:55We can create an object by using the curly braces, or by using the words new
01:01object, and in this case I'm using the curly braces and I am loading it with
01:05some initial values.
01:07After this, I have this playerFred variable that I can use, and I can add new
01:12properties freely to him.
01:14Properties are variables that belong to this particular object, and I can even
01:19add methods, which are functions that belong to this object, and then call the
01:26methods of that object. But there is nothing that would stop me, for example, from
01:30creating another object which looks like it should have a similar structure, but
01:34in this case would have high score instead of score and have level instead of
01:38rank. It just doesn't match the general structure.
01:41And this is what usually makes programmers coming from other object-oriented
01:45languages shudder because they want to define multiple objects that share the
01:49same description, and we can do this here.
01:52We can formalize our own objects.
01:55Now, for those of you coming from those other languages, no, we don't get classes
01:59in JavaScript, but we can kind of fake it.
02:02So how do we do this? Well, step one,
02:04we create what's called a constructor function to make our new objects.
02:09That really means we create a function as normal with the name that we want to
02:14use to create multiple objects from, in this case Player, and by convention we
02:19use an uppercase first letter when defining this,
02:22the same way that Date is an uppercase D and Array is an uppercase A and Regular
02:28expression has an uppercase R.
02:30Then step two is we create a new variable using the normal camelCase idea
02:36and importantly, we use the word new to create a new variable from that
02:41Player constructor.
02:43Now this will often seem a little odd the first time you see it.
02:46We have only seen the word new used before with built-in JavaScript objects like
02:51Date and Array and Regular expression, but no, we can claim it ourselves.
02:55This creates a new object and calls this constructor function for this new object.
03:01Now, there is nothing in this constructor function right now, so we might want to
03:05add a little data to the object.
03:08Well, I could put the phrase this.name=fred.
03:12If you remember, "this" is a word that we can use to refer to whatever the current
03:16object is, but I don't want to make all my objects have a name of fred, so well,
03:21here's where we use the benefit that this is a function.
03:25So what we can do instead is make this constructor function
03:28take a parameter, in this case we will call it n, and then when we call it we
03:33will actually create a new player passing in the name Fred.
03:36In this case, it will call the function Player and set the current object's name to Fred.
03:42So we now have an object with that property inside it.
03:46I could then call it again, creating another new player object, but in this case
03:51I'm creating a new object called Bob with the Bob property set inside it.
03:55So this is how I start to formalize my objects a bit more than I could before.
04:02So if I switch over to a very simple piece of JavaScript where I'm doing
04:06exactly that, I have a constructor function here and I'm calling it once using
04:11the new keyword to create this as an object.
04:16In fact, if I want to give this object a bit more in the way of properties, I am going to
04:21do it internally here.
04:22We are going to have a this.score = s and a this.rank = r, and I will make this
04:33function accept three parameters.
04:36Now, hopefully this will make a kind of sense.
04:38We are really just calling it like a normal function, passing in three parameters.
04:43But the most important piece is what I am going to do next, which is that every
04:50object in JavaScript has what's called a prototype property, and functions like
04:56the Player function I have just made is an object in JavaScript, and I can use
05:00that prototype property.
05:01What I can do is call Player.prototype.
05:08and then use this to attach to tie new functions to this player object.
05:14So I might decide that I want this object to have a method called logInfo.
05:20Now, this is completely up to me what I call it.
05:22I'm going to set that equal to and give it a function body here, and all I will
05:28do 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:41again, using this to say whatever the name property of the current object is,
05:49because we might call this with 500 different objects.
05:52I want to make sure it writes out the right one for each one.
05:56I could add another one in here.
05:58Keeping the same general format, I am going to say Player.prototype.
06:02Well, let's give this one a promote method and when promote is called it's going to say
06:12this.rank++. Add 1 to whatever the rank property of the current object is, and then we
06:19will write out a message that says, "My new rank is: this.rank."
06:32And using prototype I am attaching these functions to that constructor so it
06:38means they'll automatically be available on any object that was created
06:43using that new keyword.
06:44So down here after I create this new variable called Fred, which is a new player,
06:51I can say fred.logInfo, fred.promote.
07:02Save that, jump over and open up the page that's using this script.
07:07If I have Firefox open--yup I do-- I can see in the Console here "I am:
07:11Fred," "My new rank is: 6."
07:14Now it seems like an awful lot of trouble if I was just going to create one
07:18thing, but of course the whole benefit of this is I can now create a new
07:23variable called Bob which is a new player, and I will pass in three pieces of
07:30information--the name, the score and he rank--and I don't have to do anything
07:35else to make this object have the logInfo method.
07:40It will automatically have it.
07:42Same way it will have the promote method.
07:45I can just start calling those.
07:48Save that, jump over into the browser, refresh that, and we are getting
07:54information about the different object.
07:57Create a third one, create a fourth one, create a fifth, and so on. Each of them
08:01will act independently of each other.
08:03They will know about their own properties and they will base everything that they can
08:06do on both this constructor and any of these methods that I've attached using
08:12the .prototype property, without having to separately attached them for each and every object.
08:18Now, we are still in JavaScript, and it is a super-flexible language, so I could
08:22still dynamically start adding extra methods and properties to each individual
08:27object, but I don't need to here.
08:30Now as you might expect, you can take these idea of prototypes and of object
08:34orientation in JavaScript much deeper than this, but that's a subject for a
08:38completely different class.
08:40So for those of you looking for a somewhat more formalized object-oriented
08:44structure, this is certainly how you might begin.
Collapse this transcript
14. Putting It All Together
Example: Countdown
00:00So let's put several of these ideas together.
00:02I'm going to run through a few examples to use the techniques and the concepts
00:07we have already explored in combination with each other.
00:10And the first example I going to do here is this Countdown page, where I can type
00:16into the text box, put in, say, 3, and click the button to say Start Countdown, and I
00:21get this little JavaScript timer going on.
00:23And this is not spectacularly impressive, I grant you, but as you'll see, it's a
00:28good example of several techniques put together.
00:31Now step one, I have chosen to make this page as simple as possible, so we can
00:36focus on the script. And in fact, if I look at the HTML here, I can see there
00:40really isn't much going on.
00:42I have got a little bit of basic CSS at the top, but body of the page itself
00:46is simply a container div which inside has another div which has nothing in it and one h1.
00:55And in fact on this page itself I don't have the HTML for the text box or this button.
01:00I'm going to generate that content through JavaScript, and then I am going to
01:05add the logic to work with it.
01:07So let me open the JavaScript and show you what's going on here.
01:10First off, I have the window.onload anonymous function here.
01:15So as soon as the page is loaded, I'm going to run this code.
01:18And what we are doing here is creating a couple on new elements.
01:22I am using document.createElement here to create a new input element. It's going
01:27to be a text box, and I'm going to give it an ID of minutes.
01:31Then I'm going to create a button. Again it's an input element, but this one
01:35has a type of button.
01:37I will give it some text, which is "Start Countdown," and then I'm going to
01:41associate the click event of that button with a function called startCountdown,
01:46which we will explore in a second.
01:47And then finally these last two lines simply take my two new elements and they
01:52add them to the div called inputArea.
01:57So that's what creates these parts of the page.
02:00Now if I put in, say, some text here and click this button, it's going to pop up
02:04on alert called Please enter a number!
02:07which makes sense. Let's see what's happening.
02:11I said the click event is associated with the function called startCountdown, and here it is.
02:15The first thing we do is try and grab the contents of that text box, which we
02:20are using the.value property of, and then I am using the isNaN function to check,
02:26is it not the number?
02:28So if this minutes variable is not a number, I will pop up an alert, and then I
02:32am just going to hit return, which basically means I'm done with this function,
02:36I'm not going any further,
02:37I can't do anything else it doesn't make sense anymore.
02:40Now however, if it is a number, we will just scoot right past that if statement
02:44and then what I will do is I will find out how many minutes they typed in, I will
02:48multiply that by 60, and I will store it in the variable called secondsRemaining.
02:53Now, secondsRemaining is a variable that's actually declared right at the
02:57top of my JavaScript.
02:59It is a global variable of which I have two, just because I'm going to use those
03:03from different functions.
03:05So we create it there. What I'm then going to do is called the setInterval
03:10function. This is the one that calls a method repeatedly. And the method we
03:14are going to call is tick, and we are going to call tick every 1000 ms, which is one second.
03:19And if you remember from when we originally talked about setInterval, if you ever
03:23want to be able to clear the interval, i.e., to stop this interval from
03:27reoccurring, you need to grab a variable to it.
03:31You need to grab a handle on it, which you can then call later to
03:34call clearInterval.
03:35So we count the number of seconds.
03:37We kick off the tick function every one second, and then what I am going to do
03:41is actually hide--it's not really a form, but I am going to hide that input
03:45area that has the text box and the button, because I don't need to show it when
03:49the clock is ticking.
03:51So this must be more interesting function, which is tick, which is defined
03:54a little bit up here.
03:55Let's bring this up and just going through this one,
03:58first line I will grab hold of a variable called timeDisplay, and that is simply
04:04grabbing hold all of h1, which is showing the time. So it's just grabbing hold of
04:10this part of the page.
04:12Then what I'm going to do is turn the seconds that I have, which is stored in the
04:16seconds remaining variable, into minutes and seconds.
04:19The first thing I do is divide seconds by 60. That will give me the amount of
04:25minutes and then some number after the decimal point.
04:28So I use what's called the Math.floor function, so that's a built-in part of
04:33JavaScript, to say I want to take something that might be 4.2 and make it just 4,
04:39just make it a basic integer with nothing after the decimal point.
04:42Now I am using the term .floor rather than .round because I don't want to round up and round down;
04:48I just want to ignore any remainder.
04:51I am just interested in the minutes.
04:53Now in the same way, what I can do in this next line is just figure out what the
04:57seconds remaining are, and I am just going to subtract minutes * 60 from seconds remaining.
05:02That will give me the remainder.
05:04Several ways of course I could calculate this.
05:06On line 18 I am asking one question: how many seconds are left?
05:10And if those seconds are less than 10, I want to add a leading 0 to it, because
05:16if we are counting down, I don't want it to say 1:1. Most digital watches and so on
05:23will always have a leading zero when your seconds get down beyond 10.
05:27So this is what I'm doing here, and I am using 0 as a string, so in the double
05:32quotes, so that when these two are added together, it will turn the number 5 into
05:3705 or the number 9 into 09.
05:39I finally take both my min variable and my seconds variable and add them together.
05:44If you are bothered about official type conversion, meaning that if min is a
05:48number, how can I explicitly say it's a string,
05:51I could use the dot to string method here.
05:54I don't need to do that.
05:55This would work just fine. This concatenation will join the number that's stored
05:59in min, then a colon, and then finally, we change what the page actually displays.
06:05The last couple of things to check is did our seconds get down to 0, and if so, we
06:09can pop-up an alert saying we are done.
06:11We don't need to start calling this tick function anymore.
06:14So I will click clearInterval, and I will finally call resetPage, which is going
06:18to show the section of the page that would allow me to kick the countdown off
06:22again. And the very last line here is subtract one from seconds remaining, because
06:28this is a function that's called every second.
06:30We want to make sure that we are counting down.
06:33Finally, the resetPage function is this one line here that's going to make the
06:37input area display itself again.
06:41And that's what's going to allow us to do a little bit of error checking here and
06:46then feed in a little bit of information.
06:52And sure, this might be a simple example, but we are using it to do all the
06:59common JavaScript tasks.
07:01We are creating DOM elements, actually creating the page content
07:06dynamically through JavaScript.
07:08We are using events, both the window.onload event and also the
07:13button.onclick event.
07:14We are doing error checking of the input, making sure that in this case it is a
07:19number before we try and do anything with it.
07:21We are creating intervals to repeatedly call functions every second.
07:25We are hiding and showing parts of the page.
07:28We are using the Math object to do our calculations.
07:32We are popping up alerts, and we are grabbing and changing elements, and these are
07:37all the same things that you will be doing in every JavaScript program.
07:40Now, this example certainly isn't perfect. I could add more error checking to
07:45check for a minimum and maximum value.
07:47I could generate a pause button that might show up when the countdown begins.
07:52I could make the text change color as it gets closer to zero, and you should be
07:56able to figure out several ways this could be improved and extended.
07:59So take a look at it and see what you can do.
Collapse this transcript
Example: Resize
00:00So let's deconstruct another example.
00:03More than ever, these days we need to realize that the amount of screen real
00:07estate we have varies widely, from 30-inch-wide monitors to iPads, iPhones,
00:12and other smartphones.
00:14Now here's one JavaScript approach for dealing with this.
00:17Let's say I have a screen design for a typical desktop, and it looks pretty good,
00:21but if I resize and make it smaller, to something like a smartphone, what it does
00:26is change itself pretty significantly with the layout.
00:29Again, wider, we see a very visual display;
00:32narrow, we see a text-focused display.
00:35And the steps to do this are actually very, very simple.
00:38One, we need to write JavaScript that realizes when the screen is being resized,
00:44and two, we need to then detect the actual size of the screen, because we need to
00:48figure out is it getting made smaller or is it getting made wider and change the
00:53DOM in reaction to that.
00:55Now I could start changing individual attributes of DOM elements if I wanted
01:00to and affect things with a fine scalpel, but that's not really what I'm going to do.
01:07Instead in this case, all I'm doing is changing out the entire CSS file
01:12that this page is using from main.css, which is the default highly visual
01:17file, to narrow.css.
01:20And if I take a quick look at those, main.css is my big CSS file with a lot of
01:25stuff and narrow.css, well, there is really not much to this.
01:29In fact, this one is even doing some basic tricks like hiding all the images.
01:33So it's pretty sparse, but it proves the point.
01:36My question is well, how do you change them?
01:38And I change the CSS file by reaching into my link tag.
01:42Now up to this point, we've really been working with more visual elements,
01:47things like paragraphs and list items.
01:49But there is no reason why I can't just find, say, a link element. In this case,
01:53it has an id of myCSS, and I swap out the CSS file by just affecting the
01:59attributes of my link element.
02:01Now, this might be stored in the head section of my document, but it's perfectly
02:05accessible using JavaScript.
02:07We have been used, so far, to affecting things like paragraphs and list items, but
02:12there is nothing to stop us grabbing hold of this.
02:14We give it an ID, in this case my CSS, and I can change the attributes of this
02:20just as easily as changing attributes of any other element.
02:23So if I jump over to the script.js file, I can see what we are doing here.
02:27There's an event on the window object called onresize.
02:31We have been working with onload so far, which gets called once when the DOM
02:35fully loads, but onresize gets called multiple times when you start to resize
02:40the browser window; in fact, it gets called dozens of times.
02:43It all depends on how fast your machine actually is.
02:46It might get called a lot.
02:47So do be aware of that if the function that you are calling actually does a lot of processing.
02:52So every time it detects that the window is being resized, it will call the
02:56function called adjustStyle. That's the whole breakdown here.
03:00So the question is, what is adjustStyle?
03:02Well, it looks like there's a lot of code going on here, but in fact, we're back
03:06mainly to cross-browser issues.
03:09All I really want to do is get the width in pixels, and I create a new
03:13variable called width here.
03:14But unfortunately, there's not a super-reliable property that I can just access,
03:19because it's different across browsers.
03:22So what's happening here is we're doing another little object detection here and
03:25saying hey, do I have a window.innerHeight object?
03:28If I do, well, then I must have a window.innerWidth object.
03:31If I don't, then there is all sorts of other combinations of do I have a
03:35documentElement object, and a clientHeight object?
03:38If so, I can access clientWidth.
03:40You should not bother about memorizing this, because you're typically not going to use it.
03:46You are going either copy it from somewhere else or use a third-party library.
03:50The end result is we should have a variable called width. And in my case here,
03:55what I'm saying is if width as measured as being less than 600, I am going to
03:58take grab the CSS element and then set the attribute called href =
04:03css/narrow.css, the path to the narrow file.
04:09If it's not less than 600, we will set it to the default one.
04:12That's pretty much it.
04:15Saving that, if we open up this page, that's what detects, as we do the
04:19resize, resize down,
04:21it will change to the narrow.css. We resize up,
04:24it will change to the wide one.
04:26Now the only last thing worth pointing out is this.
04:29Let's say I resize down to a fairly small size here and then I reload the page,
04:34which as far as JavaScript is concerned means we are loading from scratch.
04:37Well, there is the problem;
04:38we are loading the default.css file here.
04:42That's because we are not actually resizing,
04:44so this is never being called.
04:47We are just opening the browser at a small size.
04:50So one of the things I really want to do here is just duplicate this function to
04:56make sure that when we do an onload the function is also called.
05:00This will only happen one extra time, so that shouldn't be a problem.
05:05Now when I refresh this page, we should load in at the correct size.
05:10Again, this is a simple example that takes us through multiple
05:14real-world requirements.
05:15We are dealing with events.
05:16We are dealing with affecting the DOM, even if we are grabbing and changing a
05:20non-visible element like link.
05:22And we are working with feature detection and object detection to deal
05:26with cross-browser issues, very much day-to-day tasks for someone working with JavaScript.
05:31And a third-party library like jQuery would let me write simpler code here and
05:36not actually worry about all this code to deal with cross-browser issues.
05:40And in a production site that's typically what I'll use, because I have more than
05:44one place that's going to need it.
Collapse this transcript
Example: Accordion
00:00And let's do an example that uses third-party libraries to add some pure visual
00:05enhancements to a page.
00:07So I have got this resources page here, and it works fine, although this content
00:11here can get a little long, a little heavy.
00:15So what I'm going to do is use jQuery and its associated language jQuery UI,
00:20which you can get through this tab here, or just from jqueryui.com, to add some
00:26eye candy to this page.
00:27Now while jQuery has some basic visual effects, like fade in and fade out, jQuery
00:34UI ads on and takes this even further.
00:37It's simply another library that uses jQuery to provide more user-
00:41interface-focused behavior.
00:43It has things like date pickers that we can use, and it has Autocomplete buttons
00:49that are really easy to start working with.
00:51And there is also a collection of effects. If you want to start animating certain
00:57behaviors on your page you can do things like pulsate certain divs or fade them
01:02or fold them or even explode them.
01:07What I'm going to do is use jQuery's Accordion, and this is very simple to use,
01:12the idea that we can have these collapsing and expanding sections of content
01:18where I click a header and get a certain section of content beneath it.
01:22And I'll be able to make this happen with one statement of JavaScript.
01:27So, how do I do this?
01:29Well, into my HTML here, what I'm going to do is down towards, the bottom I do
01:34need to link to both jQuery and jQuery UI.
01:37Now just to let you know, we've talked about the idea of content distribution
01:43networks. Both of them are available from Google's CDN, so I could grab both
01:48the path to jQuery and the path to jQuery UI, or I could store them locally.
01:53It doesn't really matter here.
01:55What I'm going to do is just put them in as script links here to the Google
01:59CDN address and following them, I'm just having a link to my own script file as well.
02:05Now before I start writing any script, of which I will need to do very little,
02:09what I do need to do is just add a few little markup pieces to my page.
02:14I need to tell the Accordion what areas it needs to control.
02:18So if I come up a little bit, what I have got here is this section. It actually has
02:24the h3 as headers and the content for the pieces that I'm interested in.
02:28I have just split it out a little bit, so we can see really a bit better where it
02:32begins and where it ends.
02:33What I am going to do first is surround the entire section with a div. I am going
02:39to give that div an id of accordion.
02:42Now I don't have to here. Accordion is not the magical name, but it will make
02:47sense. I am just going to surround the whole thing with that, opening div
02:50and closing div tags.
02:52Now inside that I need to mark out the collapsing sections, and the pieces that
02:56actually collapse are the paragraphs,
02:59so I am just going to surround them all with their own sets of opening and closing divs.
03:04I don't need to give them any ID;
03:07I just need to make sure that they have an opening and closing div around them.
03:15I'm just pasting in here when it's opening and removing the forward slash.
03:20So marking out each of those paragraphs, and finally, in my HTML the user needs to
03:26be able to click the headlines for each of those pieces.
03:30So what be accordion is going to expect is that we just mark them with a
03:34non-meaningful anchor tag, in this case a href=#.
03:41And I'm just doing that inside the h3s here, and this is all the prep that I need
03:48to do on the page itself.
03:52Just really marking it out a little bit.
03:54Now I have no CSS for according, so this is not going to make any visual change
03:59to the page yet. In fact, just to prove that, I will switch over to the browser and
04:03refresh the page, and I can see the page appears exactly as it did before.
04:07I have just got a lot of paragraphs of content, Customer notifications in
04:12a big section, and Tour voucher in the big section, Trip planning in a big section.
04:16So the final stage I have linked to the jQuery and jQuery UI, I've marked out
04:22the page here, and I need to do just one line of code.
04:25Now, in my script.js file I do have a wrapper here for window.onload, just so I
04:30didn't have to type it, and because I have jQuery, I don't need to use
04:34document.getElementById. I can just use the dollar sign. And what I am
04:38looking for is the div which I called accordion. Again, this can be any name but
04:45accordion makes a lot of sense, and in jQuery we use the pound or number or hash
04:51sign to say yes, this is ID. Accordion.
04:54Well, then what?
04:55Well, by linking to jQuery UI, we will have an accordion method. We are telling
05:01it to go and accordion itself.
05:04Save that file, and what'll happen is this div look inside itself for its own
05:09gives internally and collapse those, all of them except the first one, and then
05:14automatically add the code to allow us to expand each of the section.
05:17So I hit Save, I jump back over to the browser, I reload this, and what I've got
05:24is the first part looks just fine, but I can see that the next section is already collapsed.
05:29In fact, if I click on them, we get a little accordion eye candy.
05:36Now, the way accordions work, you only ever have one section open at a time, and
05:40it does that automatically, and it will collapse the others and take care of animating them.
05:45Now, I might add a little bit of styling to make it more obvious that these
05:49things can be clicked on, but it's working just fine. Very easy to add this with
05:54very little weight to the page.
05:56Now one of great things about jQuery UI is you don't have to load a copy of this
06:01that has everything.
06:03If I go back to the homepage of jQuery UI, I can do what's called building a
06:07custom download by clicking this button, and then I can actually simply go
06:11through and tell it now I don't need the drag drop resize interactions.
06:16I don't need most of the widgets, but I do need Autocomplete.
06:20I don't need any of the effects,
06:21or perhaps I need Pulsate. And just by selecting these, we can then download
06:27our own little copy of it that's just a zipped file with the very little
06:31JavaScript that we need.
06:33I don't need to do that right now because I just decided to link to the whole
06:37thing by using Google's CDN, but it's nice to know that it's available.
06:41And the great thing is because this behavior is all being added using JavaScript,
06:47there is no problem whatsoever if JavaScript is disabled. This page would just
06:51appear with all its parts expanded, the way it was originally designed.
06:55Now if, on the other hand, I'd written CSS to hide these sections and then only used
07:00JavaScript to open them up after the fact, we would actually have real problems
07:04if JavaScript was disabled. We would have non-readable content for people.
07:08And this once again is the idea of progressive enhancement, adding behavior
07:13to make your pages more interesting, more compelling, while remaining
07:17completely usable without it.
Collapse this transcript
Conclusion
Where to go from here
00:00In this Essential Training course we've focused on the core knowledge to get you
00:03up and running with JavaScript,
00:05but of course, this language can go much deeper than what we can possibly cover here.
00:10But now what I'm really expecting is that you have a problem you want to solve
00:14with JavaScript, and no course is going to tell you exactly what to do. So, now what?
00:18Where do you go from here?
00:20Well, we are web developers.
00:21We make use of resources on the web.
00:24We search for answers and tips and tricks, but with JavaScript you really want
00:29to be careful, because the problem is, more than any other programming language I
00:35know, the general level of advice on JavaScript is abysmal on the web.
00:40And some of the results you get, even from very popular sites that might appear
00:44highly ranked in search results, is not to be trusted.
00:48Now, most of the time that's not from malice or even ignorance, but it's just old.
00:52Some sites get highly ranked because they've been around for many years.
00:56That's the problem.
00:57We don't write JavaScript like we used to 10 years ago.
01:00So I count myself in with other trainers and authors who daydream that we could
01:04just erase all the JavaScript advice on the web and start again from scratch.
01:08But that's not an option, so be skeptical.
01:11If the answers that you find when searching involve lots of document.write or
01:15browser sniffing, that's a really bad sign. Or if in general the code just
01:19doesn't seem to know that the DOM exists, look somewhere else.
01:23So what's the alternative?
01:24Well, here are a few sites that I'm a big fan of. Probably primary and top of
01:28the list is developer.mozilla.org.
01:32This is one of the best single sources of information on JavaScript, which is to
01:36be expected, as JavaScript really comes from them.
01:39Now they have several areas on this site, but they do have a particular
01:43JavaScript section, including a full JavaScript Reference.
01:47There is a JavaScript Guide.
01:49There is ECMAScript 5 information. Great, great content here.
01:54Similarly, some of the other sites that belong to browsers such as dev.opera.com
01:58also have some terrific articles, the Internet Explorer Developer Center on
02:03Microsoft does as well.
02:05If you're using a third-party library like jQuery or Prototype, make sure
02:09that you're making good use of the site for that library and using its
02:13tutorials and its documentation.
02:16Similarly, yahoo at developer.yahoo.com/javascript has a great
02:21JavaScript developer center.
02:23Now a lot of this is focused on people who are using the JavaScript libraries
02:28from Yahoo, but there is also some great, great content there, particularly in
02:32the developer.yahoo.com/performance section, which has some great best practices
02:39for general web development and for JavaScript in particular,
02:43so definitely worth checking out when a performance issue becomes something that
02:47you're looking at closer.
02:49Now for more of a general forum, Stack Overflow is my preference here.
02:53This is a great place for questions and answers, although make sure you read the
02:57entire thread whenever you see this, because the discussion is usually as
03:01informative as the selected answer.
03:03But if I even just search on the term 'JavaScript' here, I could search on
03:08JavaScript date calculation or JavaScript jQuery or what have you.
03:13If I order by votes here, what I'm going to see is a bunch of the most popular
03:18posts under the term JavaScript. So I've got jQuery Tips and Tricks, Hidden
03:22Features of JavaScript, What should every JavaScript programmer know?
03:27And again, it's not just the list, but it's the discussion.
03:30It's the amount that get up-voted and down-voted.
03:33This stuff is all really, really good content.
03:36So I'm a big fan of stackoverflow.com as a great question-and-answer location.
03:42And last but not least, take a look at some of our more advanced courses here on
03:46lynda.com, and bear in mind, not all of them will say JavaScript in the title,
03:52because you're also going to find courses on HTML5 and on jQuery, for example,
03:57but there is some great, great content here too.
Collapse this transcript
Goodbye
00:00I hope you've enjoyed this JavaScript Essential Training course.
00:03This was designed to introduce you to the language, the core syntax of it, how
00:08to think about it, write it, start to debug it, work with the DOM, and
00:12introduce you to best practices and the kind of issues and possibilities you're
00:16likely to run into.
00:18It's now your job to take some part of this and run with it.
00:20Learning programming languages is like learning a musical instrument;
00:24you can read and watch to learn the basics, but to get comfortable, there is no
00:28substitute than hands-on practice.
00:31Now whether you're interested in the basic JavaScript functionality or going
00:35more advanced, going deeper with AJAX, exploring HTML5, or seeing what the
00:39third-party JavaScript libraries can do for you, you should be in the perfect
00:43position to do just that.
00:45JavaScript is the most important programming language on the web, and it's
00:49becoming more important as the years go by.
00:52This is a fantastic time to really learn this language.
00:55Thanks for watching. See you next time!
Collapse this transcript


Suggested courses to watch next:

jQuery Essential Training (4h 52m)
Joe Marini

HTML5: Structure, Syntax, and Semantics (4h 34m)
James Williamson



Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked