Breadth instead of depth

Now, it would be bold, and ultimately counterproductive, to include an exhaustive tutorial for each and every one of the following languages, so I won't.

We will, however, walk through the basics of each, in case you are completely unfamiliar with them.

Not covering them at all would not be fair if you have never had any contact with them, while spending too much time on any of them would counteract our goal of understanding the whole picture of a web application.

Having said that, I will now try to walk the fine line between saying too much and not saying enough on these incredibly foundational languages.

Also, I'll be introducing some other various concepts along the way, so if you are familiar with these languages already and decide to skip this chapter, check here if you think I've failed to cover something later on.

A note on the terminology "Web Languages"

You may notice that the "Ruby" of "Ruby on Rails" is not listed in the table of contents for "Web Languages". What's up with that?

What I'm referring to as "Web Languages" are those languages that are used only, mostly, or originally in a web browser .

For instance, if you've done any reading on JavaScript lately, you'll likely know that it has fairly recently been employed on the server-side as well. So while it is not used exclusively in the browser, that is what it was originally developed for.

Fiddles

Most of the code found in this chapter is accompanied by a jsFiddle that you can use to play around with the code yourself if you'd like. After you make changes, just press Run at the top and you'll see the results.

Here we go!

If you haven't done any programming before, rest assured that all of these languages are straightforward, easy to start learning, and forgiving on beginners.

And if you insist on not being assured, don't, for the love of God, be intimidated by HTML.

2.1 | HTML

Ultimately, HTML is what we were initially requesting from the server in the Google example from before. HTML dictates the general structure of what is eventually rendered in the browser. You could say that it is the "webpage", but that isn't entirely true. Remember that it also serves as a manifest of other files that will also need to be fetched to complete the page. Basically, the "webpage" as we perceive it is the sum of the three languages we're about to look at. ...and then some.

Dude. Seriously, you're killin' me. What is HTML?

Oh! Right!

HTML stands for "Hypertext Markup Language".

Furthermore, HTML is also just plain text, text just like you'd find in a .txt file, for example. It never gets compiled into some fantastical binary, incomprehensible to human eyes; it forever remains a series of characters that a human being can easily read.

In fact, if you repeat our Google request experiment from earlier using Dev Tools in Chrome but click on the "Response" tab under "Network" instead of "Headers", you'll see the HTML that Wikipedia returned to us. You'll recall that this text, which is HTML, is known as the response body.

Which gets abbreviated to "response" if we're being lazy.

You'll also recall that the browser knows how to treat it because in the response header Content-Type is set to text/html. And indeed, the response is text that is HTML.

You may also hear HTML referred to simply as "the markup" or "markup".

We'll visit another markup language later on called "XML" ("eXtensible Markup Language"), which will seem very familiar to you after learning HTML, because both are markup languages.

HTML can also be used to declare some basic styling, but, as we'll see shortly, that role has mostly been delegated to another language: CSS. But even with CSS, the general structure is defined using HTML, so it inherently defines some aspects of the default layout.

So moving forward, keep in mind that HTML:

  1. is plain text
  2. defines structure
  3. is ridiculously simple

HTML Syntax

<html>
  <p>Hello, world!</p>
</html>

Play with the jsFiddle.

There you have it, perhaps the simplest HTML document ever crafted.

The World's Simplest HTML Document™, if you will.

Enjoy forever chasing the dragon, trying to recreate this moment, because you will never have not seen HTML ever again. No not never.

Note that the HTML above is equivalent to the following: <html><p>Hello, world!</p></html>

The newlines and indentation are entirely for helping to make it human-readable, not a necessary part of the language.

So what are we looking at?

The HTML document above has two elements: an <html> and a <p>.

Both elements open and close. Taking the <p>Hello, world!</p> element as an example, the <p> tag opens the element and the </p> closes it.

The "p" in <p> stands for "paragraph" and this <p> element contains the text "Hello, world!".

So this HTML element has both opening and closing tags, with content, text in this case, in between.

There are also self-closing tags such as <br /> and <img src="image.jpg" />.

Notice that these tags have a / before the terminal > to close themselves.

More interestingly, the <p> element lives between the opening and closing <html> tags, meaning that the <p> element is the contained inside the <html> element.

From this we can see that HTML elements can contain text or other HTML elements.

They can actually contain both. That blow your mind?

...yeah, didn't think so.

Also, it could be said that "the <p> element is nested inside the <html> element".

Who cares?

When this document is loaded in a browser, you will see the text "Hello, world!". ...and nothing else. That literal text within the <p> is all that gets printed to the screen; the rest is just structure. ...really rudimentary, seemingly useless structure.

A Complete HTML document

Remember how I said that these languages are really forgiving? HTML is forgiving to a fault. Actually, more accurately, web browsers are forgiving in their rendering of HTML to a fault. That is, they don't strictly follow the HTML specification when rendering HTML.

For example, sometimes you can go as far as to leave out closing tags and the browser will still render what you meant to type.

Go around doing this intentionally though and you'll get laughed right out of your job.

DOCTYPE, html, body, and head

So, I've been meaning to tell you, I kind of lied about The World's Simplest HTML Document™.

Don't worry, the fake trademark is mine.

I lied because it's not a real, grown-up HTML document. The browser was generous and rendered it, but it cut me some slack.

To make it a full-fledge, respectable member of society, we'll have to throw in a few more elements. Take a look:

<!DOCTYPE html>
<html>
  <head>
    <title>The World's Simplest HTML Document</title>
  </head>
  <body>
    <p>Hello, World!</p>
    <p>You can call me "Brad".</p>
  </body>
</html>

Play with the jsFiddle.

Our <p> is still there, but now it's nested inside an element called <body> which is itself nested inside of <html>.

Speaking of nesting, how do we describe the elements in relation to one another?

Well, as you'll inevitably see, people treat many of the structures we'll be examining as trees and an HTML document is one of them. When it comes to relationships in HTML, the terms are conveniently borrowed from those that would be used in the description of a family tree.

...a strangely asexual family tree.

Let's say we're discussing the first <p> element.

How would we refer to the second <p>?

It is a sibling.

See how this is going to work?

What would the <body> be to either of the <p> elements?

The parent.

What about the <html> to either of the <p> elements?

An ancestor.

Additionally, both <p>'s are a child of the <body> and a descendant of the <html>. Pretty straightforward, but very useful.

Next, here's the rundown on the new elements and overall structure:

  • <!DOCTYPE html> - Declares what kind of HTML the document is. This particular DOCTYPE is for HTML5, which we'll discuss later, but there are plenty of others.
  • <html> - This guy contains everything (but the DOCTYPE) in the document, making it the root element.
  • <body> - Resides within <html> and contains all data to actually be displayed. For instance, our <p> with the text "Hello, world!" resides in the <body>.
  • <head> - Resides within <html> and contains metadata for the document in addition to acting as a manifest of other necessary files, as we'll see in a bit.
  • <title> - This lives in the <head> and its contents dictate what will be rendered in the bar at the top of the browser window.

Attributes

In addition the HTML syntax we've covered already, there is another critically important feature of HTML: attributes.

HTML elements can have many attributes. Each attribute will have a name and an associated value.

An example of this that is fundamental to the web is the "anchor" tag (<a>) which renders in a web page as what is commonly referred to as a "link".

Let's take a look at how we would make an <a> (a link) to Google.

<a href="http://google.com/">Google</a>

Play with the jsFiddle.

This is, of course, just an HTML snippet, not an entire HTML document.

Additionally, if you look at the jsFiddle for this markup, you'll see that it renders just fine in the "Result" frame, despite not being wrapped in an <html> or <body>. The reason for this is that jsFiddle does this for us, so we can just focus on writing the markup we're interested in playing with.

Notice that the opening <a> tag has an attribute href whose value is the URL http://google.com/. As you might expect, this is the address that clicking the link will take you to. The actual content of the <a> is text that is rendered in the browser as the link text.

To recap, HTML elements take the form:

<element attributeName="attributeValue">Content Text</element>

Furthermore, HTML elements contain text and/or other elements.

<element attributeName="attributeValue">
  Text content
  <otherElement>
    More text content
  </otherElement>
  Even more text content
</element>

In fact, HTML elements can have many attributes and can be nested to arbitrary depth.

id

id is a special attribute. Special in that, in a given HTML document, there must be no other element with that same id. True to its name, its purpose is to uniquely identify an element within an HTML document.

Actually, if two elements have the same id, nothing is going to blow up or flash an error in your face, because browsers are very forgiving in how they parse HTML documents.

Even so, it is invalid HTML in this case and creates a possibility for things to break subtly down the line.

Here's an example of an id in "action":

<p id="foobar">Text!</p>

In case you're unfamiliar, "foo", "bar", and "foobar" are "words" that programmers use to arbitrarily name things. Here, there was nothing special about the <p> element that I wanted to give an id to, but I did want it to have an id, so I used "foobar".

I guess you could say that "foobar" is to logic as "lorem ipsum" is to typography.

Okay, so our <p> has an id now. What can we do with that?

Well, now that it's uniquely identified, we can refer to it using hash notation. All this consists of is prefixing the value of the id with a # (read: "hash"). In the case of the id above, it would be expressed in hash notation as #foobar.

So why the hash?

Well, to give a bit of a chicken-and-the-egg answer/example, visit any fairly lengthy Wikipedia article (like the entry for HTML) and click on a link in "Contents". Now look at your URL bar. You'll see something like this:

http://en.wikipedia.org/wiki/HTML#History

See that #History at the end?

Well, in my case, the HTML for the link I clicked looked something like this:

<a href="#History">History</a>

Earlier we saw an href with the URL http://google.com/, but here we see that the href can also be used to reference an element in the page by its id. In the case of the href being #History, it would reference some element in the page that has id="History".

Be sure to notice that the # is not used in the id value; it's id="History", not id="#History".

After I clicked this link, the browser adjusted the page so that the HTML element in the page with the id History was at the very top of the page. Here's what that element's HTML looked like:

<span id="History">History</span>

We'll get to <span>'s in a minute.

The # in the URL denotes that what follows it is not part of the path, but rather information that pertains to the page.

So that doesn't really explain why hashes are used in this notation, but it is how all browsers will treat them.

And while we're talking about values we can set as an href, another acceptable value for an href is a path, which is assumed to be a path on the present domain.

For example, the path to this chapter is /chapter/2, so if we wanted to create a link to this chapter from somewhere else on the site (i.e. on the same domain), then we could create an <a> like this:

<a href="/chapters/2">Chapter 2</a>

class

class is an attribute that acts a lot like id, except that it doesn't need to be unique.

For example, the following snippet would be valid:

<p id="foo" class="foobar">Foo</p>
<p id="bar" class="foobar">Bar</p>

Also, since this is the first time we've seen an element with multiple attributes, notice that there is simply a space between the two, no punctuation needed.

The notation used to refer to elements with a particular class is to prefix . before the class name.

So we could use .foobar to reference both of our <p> elements above.

I sadly don't have a chicken-and-the-egg answer for the why of the . notation, but feel free to come up with your own.

Elements can also have multiple classes, in which case the markup will look like this:

<p class="foo bar">foobar</p>

This element could then be referenced by either .foo or .bar.

Hmm. Why exactly are we referencing our elements anyway?

That is a question we will begin to answer once we get into CSS and finish answering when we look at Ajax. It'll be great; it's a whole new dragon just waiting to be chased.

Hypertext

Okay, so we've seen the essentials of HTML syntax, but what exactly does HTML do?

Well, this is a great juncture to discuss the "Hypertext" we mentioned earlier, the one represented by "HT" in both "HTTP" and "HTML".

Hypertext is simply a term for text that is presented on a computer display that also contains hyperlinks to additional documents/files, originally just those that also contain hypertext.

On the off change you've never heard the term before, a "hyperlink" is what we now simply call a "link".

Now, you're probably thinking "Web pages have more than just text and links, dude." and you're right. The term "hypertext" has more or less come to refer to hypermedia which would cover all the other things that you're thinking of like images, videos, and so on.

The likely reason for this is that our hypertext, HTML, becomes the base structure, the scaffolding, for what ends up being a rendered web page in your browser. It definitely pulls other hypermedia in, but the page is always going to start with hypertext — HTML.

Also, keep in mind what this technology was originally intended for: sharing text over a network (i.e. the Internet).

Don't get derailed now, but this is a fascinating history that begins at CERN that is worth looking into sometime.

READERS - Did this section feel out of place? I'm not sure that it belongs at the beginning of this chapter, but I'm also not sure it belongs here.

Inline and Block

Okay, back to the markup!

So far we've seen how text makes its way to getting displayed on the screen, basic syntax, necessary structure, and some simple nesting. Our next goal is going to be to understand more involved nesting, but to do that, we're going to need to learn about two new concepts: inline and block.

These concepts manifest in many different ways throughout HTML, but perhaps the easiest way to demonstrate them is to use our good buddies <p> and <a> in an example.

<p>
  This is a paragraph that contains
  <a href="http://google.com/">a link to Google</a>.
</p>
<p>
  And this one contains
  <a href="http://github.com/">a link to GitHub</a>.
</p>

Play with the jsFiddle.

So, here we see two paragraphs, each containing text and a link.

And it the whole thing renders like this:

This is a paragraph that contains a link to Google.

And this one contains a link to GitHub.

The anchor elements is displayed inline within their respective paragraphs. This is to say that the text doesn't wrap (i.e. drop down to a new line), everything is just displayed, well, inline. This happens because <a> is an inline element by default.

Note that I said by default there, as it can be changed by CSS.

...isn't it great that I have to qualify pretty much everything I write?

Inversely, since paragraph element text does wrap (i.e. the content of the each paragraph is on its own line), this means that paragraphs are block elements.

...by default.

Also, fun fact: the text you are reading right now is contained inside of a paragraph element. There are other elements being used here and there, but most of the text on this page is contained inside of paragraph tags, which is how we end up with all these blocks of text.

So anyway, there's actually some more default styling/layout stuff that goes on with paragraphs, but the important thing to notice is that block elements don't want to exist on the same line as their siblings.

And who could blame them?

Containers

All right, now that we understand inline and block, let's look at some high-level container elements that correspond to these ideas: <span> and <div>.

These elements are mostly used to hold other elements and they do so in the exact same way, except that <span> is an inline element and <div> is a block element.

<div>'s in particular are used profusely. If you want to see an example of this, you need look no farther than Google. Try this:

  1. visit google.com
  2. right-click the Google image at the center of the page
  3. click "Inspect Element" from the context menu

Dev Tools will pop up from the bottom of the page with view of the HTML for the page, and you'll see an <img> element highlighted (the one you right-clicked on). Look at the nesting, up through its parents, and below also down through the page at the elements after it in the document; you'll see that a few <div>'s and a <span>'s are holding the <img> element (and each other) and that there are a boatload of other <div>'s on the page. These elements don't really become terribly useful until we look at CSS, but this will give you an idea of how they appear in the HTML.

But here's some quick proof of the block and inline assertions about each of them to tide you over:

<div>
  This will
  <span>all be</span>
  <span>one block</span>.
</div>
<div>
  As will
  <span>this</span>.
</div>

Play with the jsFiddle.

Images

Speaking of <img>'s, let's look at how we place images into a page.

As you look at the <img> element in Dev Tools, perhaps one of the first things you noticed was that it has a lot of attributes, but no contents. Each attribute certainly has its purpose, but the one we're going to want to pay particular attention to here is src.

src defines the URL or path to the image we want placed in the page. So which one do you see?

On my machine, I'm seeing src="/images/srpr/logo3w.png", which (as you'll recall) is a relative path, meaning that the image being referred to here can be found under the current domain (google.com).

.png is the file extension for PNG images, by the way.

To prove this, just click the path in Dev Tools to get some more detailed information, including the full URL.

Boom: https://www.google.com/images/srpr/logo3w.png

The https here stands for "HTTP Secure". More on this later in the security section.

Just as the path is relative, the URL is absolute. /images/srpr/logo3w.png could very well be a valid path on some other domain; it's ambigious. But https://www.google.com/images/srpr/logo3w.png is absolute and could not possibly be confused for any other location.

Headings

The text "Headings" above is itself a heading, an <h3> to be precise.

The "Web Languages" at the very top of the page is an <h1> and the heading to the HTML section is an <h2>.

As you can see, headings are used to describe the content that follows. Note though that the only content of a heading element is the text it displays, it does not contain the elements following it.

Right click the <h3> above and Inspect Element and see for yourself.

There are six different kinds of headings of varying sizes, from <h1> down to <h6>.

On top of helping to generally structure your page, headings also help visitors who are using a screen reader.

Lists

HTML permits two kinds of lists: ordered lists and unordered lists.

This:

<ol>
  <li>A New Hope</li>
  <li>The Empire Strikes Back</li>
  <li>Return of the Jedi</li>
</ol>

will create an ordered list that looks like this:

  1. A New Hope
  2. The Empire Strikes Back
  3. Return of the Jedi

"Erm. These are actually not the first three in the chronology of their fictional universe. So."

Yeah, I know; I couldn't think of another good example though.

Similarly, this:

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JS</li>
</ul>

will create an unordered list that looks like this:

  • HTML
  • CSS
  • JS

The default styling (the numbers/dots to the left of the items) can be removed for these and they often end up used for more general purposes.

For example, a series of nested <ul>'s make up the top navigation for this site.

Tables

Tables are used to display tabular data, like this:

Name File Extension Content-Type
HTML .html, .htm text/html
CSS .css text/css
JavaScript, JS .js text/javascript

The markup below was used to make the table above:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>File Extension</th>
      <th>Content-Type</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>HTML</td>
      <td>.html, .htm</td>
      <td>text/html</td>
    </tr>
    <tr>
      <td>CSS</td>
      <td>.css</td>
      <td>text/css</td>
    </tr>
    <tr>
      <td>JavaScript, JS</td>
      <td>.js</td>
      <td>text/javascript</td>
    </tr>
  </tbody>
</table>

We can see here that our table is enclosed inside of a <table> element that has two children: a <thead> and a <tbody>.

Each row in the table is created with a <tr>, in both the <thead> and <tbody>. The table headers are made with <th>'s inside of a <tr> and the actual tabular data themselves are created with <td>'s within <tr>'s.

Notice here that the "row" represents a single entity (e.g. HTML), while the "columns" manage a particular attribute for all entities (e.g. Name, Content-Type). This pattern will show up again when we talk about databases.

Later on, we'll end up with some <table>'s that Rails will kindly generate for us.

Forms

Traditionally, the means by which user input is collected in the browser and submitted to the server is the HTML <form>. The elements that actually hold the data the user has entered are <input> elements with various type attributes to dictate whether they are text fields, buttons, etc.

Let's take a look at an example login form:

<form action="/some/path" method="post">
  <label for="username">Username:</label>
  <input id="username" type="text" name="user[username]" />

  <label for="password">Password:</label>
  <input id="password" type="password" name="user[password]" />

  <input type="submit" value="Log in" />
</form>

Play with the jsFiddle.

Working from the top down, notice the two attributes for the <form>: action and method.

method dictates what kind of HTTP request method/HTTP verb is used when the <form> is submitted to the server.

action dictates the path used when the <form> is submitted to the server.

More on these later, but Rails will more or less handle them for us.

Moving down to the next line, we see a <label> used to identify the purpose of the <input> below it. Furthermore, the <label> is explicitly tied to the <input>, because the value of its for attribute is the same as the id of the <input>. Also note that the text content of the <label> element is displayed in the page.

Next, we can see that each of the inputs have a different type. text is for single line text entry, password is obviously for a password (with characters redacted when displayed), and submit renders as a button that, when clicked, will submit the <form> to the server. This submission is where the action and method attributes of the <form> are used.

You'll notice that the text and password fields each have a name attribute. This is used to label the values for use server-side. We'll be be seeing this in action later on.

Also, all of the <input> tags are self-closing, but the submit <input> has a value attribute that defines the text displayed on the button to be rendered.

If we wanted to, say, prepopulate the text <input> with my username, we could use value to accomplish that with something like this: <input type="text" name="username" value="forkbobomb" />.

Other common values for type are button, checkbox, and radio.

So now that we understand what all is going on here, it's worth mentioning that the formatting for this is terrible. Namely, everything is inline.

To fix this, let's make use of some <div>'s to contain things:

<form action="/some/path" method="post">
  <div>
    <label for="username">Username:</label>
    <input id="username" type="text" name="user[username]" />
  </div>

  <div>
    <label for="password">Password:</label>
    <input id="password" type="password" name="user[password]" />
  </div>

  <input type="submit" value="Log in" />
</form>

Play with the jsFiddle.

There, now we have the <input>'s for username and password each wrapped in their own <div>'s so that they will display as block.

This is certainly the cleanest way to accomplish this (and something like what Rails does for us), but we could also just force a line break using a <br />, a break tag, like this:

<form action="/some/path" method="post">
  <label for="username">Username:</label>
  <input id="username" type="text" name="user[username]" />

  <br />

  <label for="password">Password:</label>
  <input id="password" type="password" name="user[password]" />

  <br />

  <input type="submit" value="Log in" />
</form>

Play with the jsFiddle.

That was a good opportunity to see how break tags work, but seriously, use <div>'s for stuff like this. You'll thank me later.

HTML entities

Let's move on to another critical piece of HTML that we have yet to look at: HTML entities.

The primary purpose of HTML entities is to escape characters in HTML, but they can also be used as a convenience to input characters not found on the keyboard.

We'll look at the latter and move to the former.

For example, can you find the "¥" key on your computer? How about the "€" key? "™"? "®"?

Depending on where you bought your computer, you might have a couple of these, but I don't have any of them.

So how did they end up in this page?

Well, I certainly didn't hunt around the Web for them and copy/paste them here. I just used HTML entities.

Taking "¥" as an example, I can create the following:

Price: ¥1000

by using an HTML entity for the yen symbol like this:

  <p>Price: &yen;1000</p>

An alternative to the yen between the & and ; would to be to use the corresponding, unique integer identifier prefixed with a #. In this case, that integer value is 165, and so the markup above would be equivalent to the following:

  <p>Price: &#165;1000</p>

Interestingly, for values low enough, you'll notice that these integer values map exactly to ASCII character codes.

So HTML entities just exist for our convenience?

Nope, they also serve another very important role: escaping HTML.

What does that mean?

The simplest reasoning for this is best illustrated by posing a scenario and another question in response:

Assume you were writing an HTML document to teach others how to use HTML. You want to display the literal text for the paragraph tag we discussed above containing the yen symbol. How do you display HTML as text within HTML?

A first pass at this task might look like this:

<p>
  The HTML for a paragraph element with a yen symbol in its text: 
  <p>Price: ¥1000</p>
</p>

and will render like this:

The HTML for a paragraph element with a yen symbol in its text:

Price: ¥1000

Play with the jsFiddle.

So... that's not what we wanted.

This HTML defines a paragraph element with some text content and a child paragraph that contains text. The browser parses this just like it would any other HTML; it can't realize that what we really want is the literal text.

In order to get the text for the opening and closing paragraph tags to be displayed, what we ultimately want to do is to escape the < and > for each. Put more simply, we want to tell the browser that we want the literal characters for < and > there, so that it won't interpret the text representing the HTML tags as HTML tags.

So here's the second pass:

<p>
  The HTML for a paragraph element with a yen symbol in its text: 
  &lt;p&gt;Price: &yen;1000&lt;/p&gt;
</p>

and what it gets us:

The HTML for a paragraph element with a yen symbol in its text: <p>Price: ¥1000</p>

Play with the jsFiddle.

Score! The tags are showing up now!

But we're not done. You'll notice that the yen symbol is being dropped in too, when what we want is to display the literal text &yen;.

Instead of making readers of our code think: "Uhhhh, my keyboard doesn't have that, dude."

This can be accomplished simply by escaping the & at the beginning of the HTML entity, like so:

<p>
  The HTML for a paragraph element with a yen symbol in its text: 
  &lt;p&gt;Price: &amp;yen;1000&lt;/p&gt;
</p>

to finally get us what we want:

The HTML for a paragraph element with a yen symbol in its text: <p>Price: ¥1000</p>

Play with the jsFiddle.

Perfect! Ship it!

If this was hard to follow, be sure to check out the jsFiddles for each example and play around until these things make sense.

The important thing is that now when you run across this kind of problem, you'll be able to realize what's going wrong and google the proper HTML entities for your problem. ...just like I do.

Oh, and know that this was involved (read: hard) to write.

If you really want a mindtrip, think about me writing about writing about writing HTML. I ended up having to escape yet another level to get everything above to display properly.

The concept of "escaping" will come up again in other contexts, so above all else be sure to remember it abstractly. It will help later on.

Comments

The last HTML syntax feature we'll touch on is one that the browser is expected to ignore entirely: comments.

<div>
  <p>You're going to see this!</p>
  <!-- This comment will be ignored entirely and you're certainly not going to see it. -->
</div>

Play with the jsFiddle.

Why in the world would we want to do something no one ever sees it?

Well, the answer is that we, the people reading and writing HTML, are seeing it and that comments are for developers.

A terribly contrived example:

<p>The largest mammals on the planet are totally elephants.</p>
<!-- todo or maybe whales? look this up --> 

Once we have some more complicated HTML or logic, these become much more useful as flags for things we need to do or as explanations to the programmers that have to maintain code that we've written.

Perhaps even our future selves...

"What on earth was I doing here? I know I left something broken..." (Avoid this!)

HTML5, HTML4, XHTML

There are several kinds of different types of HTML that you can declare in your <!DOCTYPE>, each with different rules and features.

Throughout this guide, assume that we are using HTML5, just so we're all on the same page. That said, I won't get into the specifics of what makes HTML5 different from anything else. This is not at all because I object to the changes, but because we are instead aiming to cover knowledge that any web developer should have.

There are some exciting and promising features in HTML5 that are definitely worth checking out, but I've also heard some truly brilliant web developers go so far as to say that HTML5 is a step in the wrong direction.

The technologies that comprise the modern Web are not static, they're constantly changing and we are citizens of the ecosystem.

So don't take everything new in the Web at face value as something good. Use the tools you like and form your own opinions, but above all else be sure to be informed.

If you and I ever disagree on a technology and both for good reason, then this book has done its job in spades.

Much, much more

So that was a laughably short explanation of HTML, but you get the idea.

I highly recommend looking through some kind of dedicated HTML tutorial or reference when you're done with this book, but I'll try to explain any new HTML elements we come across them along the way.

And if I don't, a quick google search should answer all of your questions and more.

2.2 | CSS

Prepare yourself for an even more whirlwindy tour, because not only is CSS mostly out of scope for this book, I'm not a big fan of writing it.

Read: I'm not super good at design.

In most cases, CSS crosses over to the design side of web development; and while there is some truly brilliant stuff done there, our focus right now is to understand web mechanics, not aesthetics.

So why mention it?

Well not only is CSS integral to understanding the full front-end picture from a browser perspective, there are also quite a few features that, though arguably aesthetic in nature, are used to affect functionality using CSS.

We won't see evidence of that until we talk about jQuery, but trust me, it's big.

... What do I have to do to get an acronym definition at the beginning of a section around here? ...CSS?

Cascading Style Sheets! Now aren't you glad now that I gave you such a great lead-in (see above) rather than just broadsiding you with that nonsense?

The name does make sense though, in an annoying, esoteric kind of way.

Can you tell I'm not the biggest fan of CSS?

The way that CSS is tied to design is that its purpose is to change the style of elements, hence "Style Sheets". Just as the focus of HTML is structure, the primary focus of CSS is styling. Furthermore, this styling achieved using CSS can also change aspects of the default layout set by the HTML.

"Cascading" refers to the nature in which one line of CSS can define a style for a given element and then have that style overridden by a subsequent line of CSS. Because of this, the style definitions are said to "cascade". We'll see this later.

Lastly, CSS is not some magic, proprietary format. Like HTML, it too is just plaintext. As you might expect, the Content-Type for CSS is text/css.

CSS Syntax

To understand CSS, we're going to play around with some, and to do that we're going to need a snippet of HTML to apply it to.

<div id="ch01" class="chapter">
  <p id="ch01v01" class="v01 verse">
    In the beginning was HTML.
  </p>
  <p class="v02 verse">
    Then CSS came along.
  </p>
</div>
<div id="ch02" class="chapter">
  <p class="v01 verse">
    But then what? 
  </p>
</div>

Play with the jsFiddle.

So let's say we want to make the text for the first verse blue instead of black (which is the default). To do this, we're also going to have to assume we're awful at design.

It won't be a stretch for me.

We can accomplish this with:

#ch01v01 { color: blue; }

Play with the jsFiddle.

The format seen here is selector { property: value; }. In this case, the selector is for an id, so it uses the # prefix to become #ch01v01.

If we wanted the second verse to have blue text as well, we might first write something like:

#ch01v01, #ch01v02 { color: blue; }

Play with the jsFiddle.

Notice how the two selectors are separated by a , and that the property will be applied to both.

Now, this works just fine if we only want the first two paragraphs to have blue text. But what if we wanted was for all the verses in the first chapter to have blue text?

As things stand now, if one was added later, it would not receive the (ugly) styling we defined above. We can easily future-proof for this situation by rewriting our CSS:

#ch01 .verse { color: blue; }

Play with the jsFiddle.

The important thing to note here is the lack of a , in the selector. It would read in English something like "all verses for chapter one will have a text color of blue."

In fact, we could have accessed #ch01v01 with #ch01 .v01 and #ch01v02 with #ch01 .v02 earlier.

In the case that we only mean all future <p>'s of class verse, we can change the CSS again to explicitly declare that:

#ch01 p.verse { color: blue; }

Play with the jsFiddle.

All verses?

.verse { color: blue; }

Play with the jsFiddle.

All <p>'s?

p { color: blue; }

Play with the jsFiddle.

What if we really wanted to assault the user's eyes and toss that blue text on a red background for the paragraphs as well?

p { 
  color: blue; 
  background-color: red; 
}

Play with the jsFiddle.

So there you have it, you've seen how values are set for multiple properties, how to use multiple selectors, and how selectors can be chained together for more specificity.

More On Selectors

We've now seen the basics of CSS, but there are some other features to keep in mind.

First, what if you wanted to make the text blue for every element?

* { color: blue; } 

Play with the jsFiddle.

This is not the way you'd want to go about doing this, since you'd probably want to just set it for all elements that are meant to display text, but * does act as a wildcard selector for all elements. It can also be chained in a selector like #ch01 * to mean "every element in #ch01".

* is almost always a bad idea because it's incredibly slow, due to the way browsers process CSS. This is not to say it never has a place, but be careful and incredulous.

Next, what if you wanted only to select the direct children of an element, but not all ancestors? More specifically, what if we needed a selector for just the <p> that are children of our chapter <div>'s above?

That would look like this: .chapter > p

All child elements of every .chapter?

That would be .chapter > *.

Pseudo-classes

Psuedo-classes allow us to make more granular selections like this:

#ch01 > p:first-child { color: blue; }

Play with the jsFiddle.

The selector above reads as "the first child of #ch01 that is a <p>".

They also allow us access to things like colors for a links to a page that has been visited before:

a:visited { color: orange; }

Some of these won't work uniformly across all browsers and their use is therefore discouraged. Luckily, we can do this stuff with jQuery instead.

Display and Visibility

The display property is one that gets a lot of use for more functional purposes.

Remember our discussion on "inline" versus "block"? From a CSS standpoint, those are both values for the display property.

As you'll recall, <p>'s are block elements by default. If we wanted to change that we could do the following:

p { display: inline; }

Play with the jsFiddle.

In the example of chapters and verses above, the verses of each chapter would all be on a single line. The chapters would be on separate lines though, because <div>'s are block elements.

Going back to the idea of absolute versus relative, this proves to be an absolute change (in the context of the document) that we probably don't want to make. If we had a full HTML document instead of a snippet, we'd probably have other <p> elements on the page that weren't verses and would probably want them to continue to display as block. Because of that, a more reasonable adjustment to the CSS would be a more specific, relative one such as this:

.chapter p.verse { display: inline; }

Play with the jsFiddle.

You may be wondering if the p in p.verse is necessary; it isn't.

Why's it there then?

Sometimes the least amount of typing isn't the most maintainable solution and it's nice to make your code more self-documenting so that it's easy to read. When you do this, you're not just doing it for others, you're doing it for your future self.

Coming back to this line of code months later just to see .verse instead of p.verse might leave you to do some searching through your markup.

"What kind of element was .verse?"

"Why didn't I just use an inline element in the first place?"

That is the question we probably should be asking.

This is another instructive example of something that works in practice, but doesn't really make sense. If we wanted the verses to display inline, we'd be much better off wrapping the text in <span> tags (whose job is to display inline) rather than <p> tags.

Often times you can get so involved in what you're doing while developing that you miss the best way to achieve your desired result.

Working our way through this example, we can see a flawed thought process. Instead of asking "how can I get these paragraphs to display inline?", we should have asked "How can I get these verses to display inline?" The difference is subtle, but an important one. Ultimately, <p>'s are semantically meant to be display block and <span>'s are semantically meant to display inline.

Anyway, back to display. If you look into the display property, you'll find many more values for it besides block and inline, but there is one in particular that is also used rather frequently: none.

If we were to write the CSS #ch01 { display: none; }, #ch01 would disappear and #ch02 would move up to fill its place.

Play with the jsFiddle.

This particular feature gets used frequently by front-ends heavy in jQuery, so be sure to remember it.

But what if we don't want an element to move up and fill in a display: none element's place?

And what if we can't think of an instance of that mattering?

It does, trust me.

In that case, we don't want display at all, we want visibility. In order to not display the element, but for the browser to treat the element as if it were still there, we would write #ch01 { visibility: hidden; }

Play with the jsFiddle.

Hidden, cool. What if we want to bring it back?

Well, that value for visibility would simply be visible.

In fact, let's run these two together to demonstrate the "cascading" nature of "Cascading Style Sheets".

#ch01 { 
  visibility: hidden; 
  visibility: visible; 
}

Play with the jsFiddle.

The visible cascades over the previous hidden value and we end up with the element visible on our page.

Size

When it comes to sizing an element, you'd probably expect that we have control over width and height. We do.

What you might not expect is that we have three other qualities related to these: padding, border, and margin.

Each of these also has -top, -right, -bottom, and -left variants as in padding-top or margin-left.

This is yet another wildly out-of-scope topic, but something that does need to be covered. So let's take a peek at an element in Chrome with Dev Tools.

Right click the lorem ipsum text below and Inspect Element:

Lorem ipsum dolor sit amet.

This will land you in the Elements tab of Dev Tools, with the <pre> tag you just right-clicked highlighted in the HTML.

the <pre> tag selected in Dev Tools

<pre> tags are traditionally used for "pre-formatted" text, but they are also used by Twitter Bootstrap (which this site uses) for displaying multi-line code blocks. Because of this, they have styles applied that pertain to exactly what we're talking about.

Now, look to the right side of Dev Tools and you'll see Computed Styles and Styles. The downward-facing arrow/triangle in front of Styles indicates that it is "open". Click on Styles to close it so we can see all of our options.

"Styles" closed

Next, click Metrics.

"Metrics" in Dev Tools

Now we see a series of nested rectangles and the text margin, border, and padding; we're in the right place.

Hover your mouse over each of these labeled triangles and watch how the corresponding parts of the <pre> element are highlighted in the page.

hovering over margin in "Metrics"hovering over border in "Metrics"hovering over padding in "Metrics"

And finally, hover over the inmost rectangle.

hovering over width and height in "Metrics"

The values inside of this one takes the format width x height.

From this we can see that a border is exactly what it sounds like, something that runs around the outside of the element.

We can also see that padding is used to pad the inside of an element and margin is used to create space outside of an element.

There are many subtleties to these properties that are too numerous to detail here, but now we are at least familiar with the basics of what they each mean.

Position

position and float are two other properties worth looking into later. You can find tutorials pertaining to these on the resources page.

Comments

And as you might expect, CSS has comments as well. They look like this:

/* this is a comment */

/*
so is this
*/

A Couple More Things

If you don't want CSS to do its whole "cascading" thing and you absolutely want a style to stick around regardless of what follows, you can use !important before the ; in your style definition.

It looks like this:

#some-element { display: none !important; }

This is usually not the right way to do things and it'll probably come back to bite you later, but it does work and can prove helpful.

HTML style tag

Something we overlooked earlier is that we can also define styles directly within an element by adding a style attribute. Styling this way is largely discouraged because it often conflicts with actual CSS in rather confusing and frustrating ways.

You have been warned.

Even so, the style attribute does have its applications and is worth understanding.

For example, jQuery's .css() "modifies [an] element's style property."

Why is this okay?

Because it is _modifying the style property. The style attribute isn't normally a problem unless you've hardcoded a value for it into your HTML. The only time this is even a remotely good idea is if you are prototyping (and have a fantastic memory).

Here is an example of a couple of <p> tags with inline styling:

<div>
  <p style="color: blue">Blue text.<p>
  <p style="color: blue; font-size: 32px;">Big, blue text.<p>
</div>

Play with the jsFiddle.

To Google!

For the love of all things digital, please do not let your CSS knowledge end here. Having read this section, you're certainly equipped to understand more properties, so have at it!

As I mentioned before, using CSS selectors gives us an idea of why and how we would target HTML elements. This will serve us well when we discuss jQuery later on because jQuery uses the same kind of selector syntax, but for a different reason.

Speaking of, jQuery is a JavaScript library. Ready to see just exactly what JavaScript is?

I am!

2.3 | JavaScript

READERS Please let me know if any of the jsFiddles don't match or don't work properly below. Thanks!

JavaScript, also referred to simply as "JS", is a kind of programming language called a scripting language.

The term scripting language has quite a few meanings, but perhaps the most important to us here is that this means JavaScript is distributed and executed as plain text. This makes the Content-Type for JavaScript text/javascript.

Have you noticed the pattern here? All of these languages are sent to the client as plaintext. This is incredibly convenient because it allows us to use Dev Tools and the like to inspect all the different HTML, CSS, and JavaScript files pulled in by a given page.

Certain programming languages must be compiled (converted into binary code) in order to be run. Both of the programming language we'll be looking at in this book (JavaScript and Ruby) do not need to be compiled. As scripting languages most often are, both languages are interpreted languages, meaning that they are executed at runtime by an interpreter instead of a compiler.

This distinction is one worth looking into later, but for right now we don't need to be bothered with it.

Another convenience of Dev Tools is that we can execute arbitrary JavaScript within the browser.

To check out this awesome feature go to Chrome and:

  1. hit F12 to get Dev Tools pulled up
  2. click on the "Console" tab
  3. type in 2 + 2
  4. hit ENTER on your keyboard

And you'll see 4 output in the console below your 2 + 2.

You've just written JavaScript!

"Oh wow, my computer just added two and two for me, I'm super impressed."

I know, right?

Now, try the same thing without the spaces, 2+2, instead.

Same result. The reason for this is that JavaScript doesn't care about whitespace. Examples of Whitespace characters are spaces and tabs.

So that's not very exciting; we're just getting 4 to print to the console, and it wouldn't even be displayed to a normal user.

Well, how would we go about displaying it to a user?

Overarchingly, that's basically what we're here for: how do we perform some data operation and present the appropriate result to the user?

Most of the normal mechanisms for doing this require an understanding of some other concepts, but there is an incredibly simple one that we can use straightaway: the alert.

Let's head back to the console:

  1. type alert(2 + 2) into the console
  2. hit ENTER

Now we're talking. We just made an alert pop up that says 4.

But what exactly happened there? alert makes sense, but what's with the ()'s?

There are a number of things to address here, but let's start off with an observation:

The alert contained 4 instead of 2 + 2.

So, clearly, the mathematical statement 2 + 2 was evaluated, resulted in 4, and that value was then alerted.

When the browser parses the JS, the 2's are seen as integer literals. More generally, it can be said that 2 is of the type number. To prove this, just run typeof(2) in the console.

To be more specific, 2 is an Integer, but typeof won't get that specific. The other number type is Float. Float is short for "floating point", which is a term used in programming to refer to decimal values. An example of a float would be 2.0.

As for the +, it's parsed as an operator. This obviously means that it performs some kind of operation and it does; here it's addition.

So then in the case that we wanted to alert the equation itself, we wouldn't be interested in number literals or operators at all; we would want a string literal. In programming, a "string of text" is referred to as a string. In JavaScript, strings have the type, well, string.

Despite trying, I have never found one canonical answer as to why they're called strings.

So let's take a look at how we would alert the string representation of the equation:

alert("2 + 2")

Play with the jsFiddle.

Here we see that that we can use ""'s to create a string. Notice that the double quotes themselves are not displayed in the alert, but are instead a means of creating a string in JavaScript.

Hmm, do strings do something special with numbers?

Not at all; strings are simply used for text, so they treat the numbers as literal characters instead of mathematical entities.

Now, here's a question for you: What do we do when we need to put literal " characters in a string?

See the problem here?

If we place another " in the middle of a string, that would actually just close the string.

So let's look at some solutions.

If you're wondering if we need to escape the " character (similar to what we did with HTML entities earlier), then you're getting the hang of this.

There are actually a couple ways to solve this, escaping the characters being one of them, but perhaps the easiest way is to simply use ' to define the string instead of ", like this:

alert('"Boom. Literal quotes."')

Play with the jsFiddle.

Since this uses single quotes to create the string, the line above will alert "Boom. Literal quotes.".

Problem solved, right?

Well, there's a related case where this won't work as is.

Let's think "what about alerting all of this?"

See the problem with the text above?

The text above uses both of the quote characters that we can use to create a string.

So what do we do?

This is a case that requires escape characters. Since there are two "'s and only one ', I'm going to wrap the string in single quotes and escape the lone single quote in the string. Check my work:

alert('Let\'s think "what about this?"')

Play with the jsFiddle.

See what I did? The backslash in Let\'s says "treat the next character literally and put it straight into the string, it doesn't hold any programmatic meaning".

If you try:

alert('Let's think "what about alerting all of this?"')

without the escaped quote, you'll find that JS doesn't care for that at all.

At this point you might be thinking: could we have wrapped the string in double quotes instead?

Absolutely.

Can you guess what it looks like?

alert("Let's think \"what about this?\"")

Play with the jsFiddle.

It's also worth mentioning that you could still escape the ' and get the same result.

alert("Let\'s think \"what about this?\"")

One thing to be aware of here is that there are a number of escape characters in JavaScript, the most common of which is undoubtedly newline, represented inside a string as \n. Text after a newline will wrap and display below any text preceding it.

To see how this works, try this:

alert("foo\nbar")

Play with the jsFiddle.

All right, so now we understand how we would output the equation from alert(2 + 2) if we wanted, but it did sum the two numbers to 4. Let's take a closer look at this.

Frequently, when you see ()'s in JavaScript it is for the purpose of a function call, which is to say that the programmer is calling a function. This is the case for what we see with alert(...). More specifically, we are calling the alert function and passing it 2 + 2. An important thing to notice is that 2 + 2 is executed and its return is 4, which is then alerted.

What is a "return"?

Take our 2 + 2 in the console for example. After we executed the code 2 + 2, we saw 4 output below it. The reason for this is because 4 is what the operation we ran returned.

Everything we do in JavaScript is going to return something. ...except when it doesn't. That is, a line of JavaScript will always return something, but that something might be nothing.

What on earth are you babbling about?

Right? Bear with me.

Try re-running any of the alert code we've written, close the alert, then look at the last line of output in the console.

Re-running a command in the console is easiest done by hitting the UP, then ENTER. You can also hit UP repeatedly to go through even earlier code.

See that undefined? Try typing undefined into the console and then ENTER. This will return undefined. Then try typeof(undefined). This will return "undefined".

From this we can see that undefined is a (special) value in JavaScript and is of the type "undefined".

undefined has a rather unique purpose in the JavaScript ecosystem of being the value that says "not only is there nothing here, nothing was ever here". It's actually not alone in being "nothing" as we'll see in a while, but for now just be aware of undefined and understand that everything returns something, even if it's nothing.

So now that we understand returns, let's go back to talking about those parens, which means we should start talking about functions.

Functions

In fact, taking a look at JavaScript functions is actually a pretty great idea, because functions are at the heart of what makes JavaScript such a great language.

To kick off our survey of functions, let's define one of our own. All it will do is serve as a wrapper to alert(), but it will be ours.

Type the following or copy/paste it into your console in Chrome:

function customAlert(str) {
  alert(str)
}

Note that this is equivalent to function customAlert(str) { alert(str) }, but that the JavaScript parser doesn't care about the newlines/whitespace.

So let's walk through this step by step.

The function keyword indicates that we are defining a function.

customAlert is the name of our function.

The ()'s after the function name house the parameter list, values that are passed into the function. We define only one parameter for our function: str (common abbreviation for "string").

After this is the code that will be executed when the function is called which is surrounded by {}'s.

Then, within the function, we simply call alert and pass it the argument str with the line alert(str).

The distinction between the term "parameter" and the term "argument" can be seen above: "parameter" is a term for something used in the function definition, while "argument" is a term for something passed in during a function call.

For example, the "2 + 2" inside our alert(2 + 2) from before is also an argument.

Having said that, you will undoubtedly hear them used interchangeably at some point (probably even from me), but know that there are some people that really hate that. I've found that a lot of people don't understand the distinction themselves, don't care, or will cut you a break if you confuse the two, but this is something you'd want to get straight for, say, a job interview.

With that, I'm probably going to go back to carelessly calling everything an argument, because that's how I roll.

Now that we have our function defined, let's call it:

customAlert(2 + 2)

Play with the jsFiddle.

You'll notice that calling our function causes the same outcome as our original alert(2 + 2): it outputs 4.

So in the call customAlert(2 + 2) our 2 + 2 is evaluated, returns 4, and that 4 is passed as an argument to customAlert just the same as if we had instead written customAlert(4).

Inside of customAlert, 4 is kept track of by giving it the name str (defined as a parameter in the function definition).

We then make a call to alert again, passing str as an argument in alert(str), which is the same in this case as if we had written alert(4).

Operator Precedence

It's worth noting that though the ()'s are used here to call the function, parens can also be used in JavaScript to change operator precedence.

In fact, the way they do it greatly resembles the mathematical notation used to override order of operations. For instance, mathematically 2 * 2 + 2 = 6 (where * is the multiplication operator) but 2 * (2 + 2) = 8. In JavaScript, 2 * 2 + 2 will return 6 but 2 * (2 + 2) will return 8.

Operator precedence is actually its own topic, but for now just understand that things in parens are forced to run first.

In fact, when in doubt, wrap anything you want run first in parens.

Eventually, we end up with an alert saying 4 in front of us. Success.

Another Function

Now that we have some understanding of functions, let's write a more involved one.

Let's say that we want a function named add that takes two numbers as arguments, sums them, and then alerts the equation and result.

For example, if we called this function as add(2, 2), then we should see an alert that reads 2 + 2 = 4.

Notice that arguments are separated by commas in function calls; the same holds true for parameters in a function definition.

Here goes.

function add(num1, num2) {
  sum = num1 + num2;
  str = num1 + " + " + num2 + " = " + sum;
  alert(str);
}

We'll walk through line by line, but one of the first things that you should note is that each line is terminated with ;. A ; is to a line of JavaScript as a . is to an English sentence. Up to this point, we've only been executing a line at a time or a single line inside of a function, so we haven't needed (and haven't bothered) to use any ;'s.

But we still could have.

If you defined the function above in your browser console, you can run it with add(2, 2), which will get you an alert that reads 2 + 2 = 4.

Play with the jsFiddle.

The blow by blow:

  • function add(num1, num2) { - function definition for add, which will take two args: num1 and num2
  • sum = num1 + num2; - add num1 and num2 together, saving the returned value as a variable named sum
  • str = num1 + " + " + num2 + " = " + sum; - concatenate a string together to describe the full equation, saving it to a variable named str
  • alert(str); - alert the value of the variable str
  • } - close the function definition

Variables

The most pressing question is of course: What is a variable?

Variables are named buckets into which we can drop literal values.

"Wow, buckets. How technical."

I'm sure there exists a much more technically accurate explanation, but variables are used to store values and they have names. If you're familiar with algebra, the concept is essentially the same.

Also, it's worth noting that the contents of variables are held in memory (RAM, that is).

We can store values of any kind in a variable. We can also change the value of a variable.

Hence the name "variable".

num = 2;
alert(num);

num = '4';
alert(num);

Play with the jsFiddle.

Variable names can contain lower and uppercase letters, as well as numbers, _'s, and $'s, but they cannot begin with numbers.

String concatenation

So inside of add, what is all this noise? num1 + " + " + num2 + " = " + sum

There are several things to address here, but perhaps it would help to identify exactly what we have here. Looking closely we can see:

  • four + operators
  • three variables (num1, num2, sum)
  • two string literals (" + ", " = ")

All the special characters and whitespace can make this a pain to read, but look closely and you'll see they're all there.

What's does it all do?

This line ends up joining a bunch of values to create the complete equation string. When strings are put together this way it is referred to as concatenation.

"But all of the variables contain numbers, not strings!"

We'll get to that in a minute.

We can concatenate two strings using the + operator. Let's try doing this with 'foo' and 'bar' and alerting the result:

alert('foo' + 'bar')

Play with the jsFiddle.

Now let's try a different call to add. What do you think would happen if we instead ran add('2', '2')? Give it a go.

Play with the jsFiddle.

Hmm, 2 + 2 = 22.

See what happened? The + operator means something different to strings and numbers: it will concatenate strings but sum numbers.

So our line in charge of the concatenation returns a string when evaluated, but why does that happen when the values we passed in are of type number?

Your answer after a definition and explanation.

Loose typing

JavaScript is what is referred to as a loosely typed language. What this means is that you the programmer do not have to indicate the type of a variable (or parameter) when defining it.

Loose typing is also more pejoratively referred to as weak typing. ...at least I've always thought it sounded like a put down.

So instead of something like String name = "Brad Chase"; (as you would see in a language like Java), all you need is name = "Brad Chase". In fact, we're not even allowed to use the former.

While this saves us a few keystrokes and can make mixing types straightforward, it also introduces the potential for errors and other generally unwanted results at runtime, as we saw with our 2 + 2 = 22.

For instance, you might think you have two numbers held in two variables and when you + them together you instead get a concatenated string of the two. Woops, you actually had to strings.

This is exactly the problem with our 2 + 2 = 22 above.

So going back to our question of why the sum ends up as a string when both numbers and strings are involved, let's drop number literals in and walk through what happens per +.

Here is what our example would start with: 2 + " + " + 2 + " = " + 4

And here's how it would progress:

  1. 2 + " + " » "2 + "
  2. "2 + " + 2 » "2 + 2"
  3. "2 + 2" + " = " » "2 + 2 = "
  4. "2 + 2 = " + 4 » "2 + 2 = 4"

The key to all of this is that a number and a string cannot be +'d together, but since JavaScript is loosely typed, it makes the assumption that what we want is the string representation of the number concatenated with the string.

And it does just that.

Something worth mentioning here is the += operator. It will add/concatenate to the value of a variable and then save the result back to the variable.

Examples work best as an explanation for this I think.

num = 2; num += 2; 

Leaves num with a value of 4. Equivalent to num = 2; num = num + 2;.

str = 'foo'; str += 'bar'; 

Leaves str with a value of 'foobar'. Equivalent to str = 'foo'; str = str + 'bar';.

str = 'lucky'; str += 7; 

Leaves str with a value of 'lucky7'. Equivalent to str = 'lucky'; str = str + 7;.

Play with the jsFiddle.

That last one works thanks to loose typing. The reverse, equivalent to 7 + 'lucky', would be just fine too.

There are also -=, *=, and /= operators that work similarly, but only for numbers.

Typecasting

But say we have have "2" and "2" for our arguments to add. If we know that they are strings representing number characters, how do we add the numbers they represent together instead of concatenating them as strings?

JavaScript accommodates this by letting us typecast a value from one type to another. There are a couple ways to do this, both of which are functionally equivalent:

Number('2') and parseInt('2') will both return 2.

We could also explicitly cast the variables to strings for our earlier example.

String(num1) + " + " + String(num2) + " = " + String(sum)

This might be overkill here if we are pretty sure we're going to have numbers for both arguments, in which case we know the casting will just be handled automatically. Keep in mind that there are some cases arise where you will want to make sure though.

Let's apply this to rewrite our function, this time typecasting both of our arguments as numbers:

function add(num1, num2) {
  sum = Number(num1) + Number(num2);
  str = num1 + " + " + num2 + " = " + sum;
  alert(str);
}

Play with the jsFiddle.

Our Own Return

So we've talked about different things returning a value, but do functions have returns?

Yes. In fact, we just saw parseInt('2') return a 2.

But you might have noticed that all of the functions we've written so far have just returned undefined.

If you've been running them in the Chrome console.

So what would we do if we wanted add to alert the sum of the two arguments and return their sum? That is, what would we do so that add would also return 4 from the call add(2, 2)?

This can be accomplished with the return keyword:

function add(num1, num2) {
  sum = Number(num1) + Number(num2);
  str = num1 + " + " + num2 + " = " + sum;
  alert(str);
  return sum;
}

Score.

What happens to that value?

We could totally keep it in a variable:

sum = add(2, 2)

Play with the jsFiddle.

Awesome. sum now has the value 4.

You might notice in addition to the sum variable we just defined, there is also a sum inside of our add function. Does JavaScript get confused by this?

No, but we human beings certainly can! We'll dig into this later when we talk about scope.

Two notes in regards to return:

  1. return; is also valid and will return undefined
  2. after a line with return is executed, nothing else in the function is run

These can be illustrated with a simple function:

function nothing(){
  return;
  alert("Yain't ne'er gon' see this.");
}

alert(nothing());

Play with the jsFiddle.

Note here that nothing takes no arguments, so it's defined as function nothing(){ ... }.

Also, we're passing the return from our call to nothing() directly into alert() when we do alert(nothing()).

More on functions

Now that we have an understanding of how to define and call functions, let's take a more detailed look.

To kick things off, let's look at an alternate way to define a function. The following two definitions are equivalent:

  1. function add(num1, num2) { return num1 + num2; }
  2. add = function(num1, num2) { return num1 + num2; }

Technically, the first of these utilizes the function statement, whereas the second uses the function operator.

This is definitely an interesting topic to look into, but for now, just know that you can use either.

The second syntax is possible because functions can be passed around as values.

To illustrate this from the console try the following:

foo = function(){return 'baz'};
foo;
foo();
typeof foo;
bar = foo;
typeof bar;
bar();

With that, the function foo is copied to bar.

Also, notice that foo is the function, but adding the (), as in foo(), will call the function.

Using the same logic as foo = function(){ ... } where we used the function operator to essentially set the function as a value to a variable, we can also pass a previously defined function or even an anonymous function as an argument to another function.

callFunctions = function(func1, func2) { func1(); func2(); }
foo = function() { alert('foo!'); };
callFunctions(foo, function(){ alert('bar!') });

Play with the jsFiddle.

Take a close look at that last function call and you'll see that a bunch of things are closing all at once, resulting in )}).

These sorts of things can get hard to read, so do those maintaining your code (and your future self) a favor and work to make things as readable as possible using whitespace and named functions where appropriate.

"Then why'd you leave it like that?"

Because you'll run across it somewhere, and now you're prepared.

Let's break this down.

We see that callFunctions is a function with two parameters: func1 and func2. These are presumably both functions and both are called with func1(); func2(); within the function.

In callFunctions(foo, function(){ alert('bar!') });, foo is the first argument and function(){ alert('bar!') }, an anonymous function, is the second.

Why would anyone ever want to do this?

Believe it or not, there are applications for this and we'll be taking a look at a few of them when we get into jQuery and Ajax.

There is one more thing to be mentioned in regards to anonymous functions: self-calling functions.

These are also referred to as self-invoking functions or self-executing functions.

(function(){
  alert('Here!');
})()

Play with the jsFiddle.

Notice that the function is wrapped in () which will return the function as a value and then that function is called with (). Lots of ()'s and {}'s here, so look carefully until you see what's happening.

The ()'s around function(){...} are syntactically unnecessary here, but call attention to the fact that this function is doing something different (self-executing).

If we were to (counterproductively) give this function a name, it would look like this:

func = function(){alert('here')}; (func)();

This would be silly because we can equivalently call func with func(), but this is the same thing we were doing with the self-calling anonymous function above.

This may seem incredibly useless (and continue to seem that way for a while actually...) but framing it in the context of our next topic will give us at least one reason for doing this.

Scope

JavaScript makes use of what is referred to as function scope.

Let's start our look at this topic with an example:

var a = "OUTSIDE";
alert(a);

(function(){
  var a = "INSIDE";
  alert(a);
})();

alert(a);

Play with the jsFiddle.

This code will alert: OUTSIDE INSIDE OUTSIDE

See what happened?

There is an a outside the function and an a inside the function, but the value of the outside a remains the same even after add is called and its inner a variable is set.

You'll probably also notice that there's a little something extra here: var.

We could say that var is new to us, but that wouldn't be entirely true. When we declare a variable with a name not used before, it gets treated as if it has a var in front of it. The difference here is that we are throwing a var in front of a variable name that is already defined.

To see the difference, let's look at two similar examples:

var a = "OUTSIDE";
alert(a);

(function(){
  alert(a);
  a = "INSIDE";
  alert(a);
})();

alert(a);

Play with the jsFiddle.

This code will alert: OUTSIDE OUTSIDE INSIDE INSIDE

We don't tack a var onto the front of a = "INSIDE"; here and that allows us to access and modify the a variables from the context above.

More on context shortly.

var a = "OUTSIDE";
alert(a);

(function(){
  alert(a);
  var a = "INSIDE";
  alert(a);
})();

alert(a);

Play with the jsFiddle.

This code, however, will alert: OUTSIDE undefined INSIDE OUTSIDE

It also proves that we can use the same variable name within a function without affecting that variable in the context above when we declare that variable with var.

Perhaps the strangest part about the second example is the undefined alert value, but that too can be explained.

The var a basically says "I am going to be using a new variable a here". So within the function that contains that var a, JavaScript will initialize a fresh variable for the context of that function to a = undefined before any of our code for that function is run.

This process is called a variable declaration, which is distinctly different from a variable definition because it does not assign a value.

...if undefined is "not a value".

In fact, we can perform a declaration ourselves with var a; all by itself and then set a value to the variable later, but this is equivalent to doing var a = 'some value'; anywhere in the function because of the way JavaScript handles the var keyword.

If any of this seems particularly confusing, it pretty much is initially. At least it was for me.

But don't worry, save for the occasional confusing behavior from your code, you can get away without having this completely nailed down. Plus, now you're at least aware!

For much, much more on this topic, please watch the Douglas Crockford videos on JavaScript listed on the resources page.

Objects

Another of the core JavaScript types is object.

If you are at all familiar with object-oriented programming, be sure to note that JavaScript uses prototypal inheritance rather than classical inheritance (like you would find in languages like Java).

Also, frequent use is made of object literals without rigid definition as to their structure, because they are used as the hashes/associative arrays of the language.

Let's jump in with an example:

game = { title:'Left 4 Dead' };
alert(game.title);

Play with the jsFiddle.

The {}'s above are used to create as an object literal, one that contains one property/value pair title/'Left 4 Dead'. That value 'Left 4 Dead' is later retrieved in the alert call by using the . syntax in the form game.title.

You may also hear object properties referred to as "keys".

Now, having run the code above, we can change the value assigned to that same property.

game.title = 'Half-Life 2';
alert(game.title);

Play with the jsFiddle.

Adding on again, let's insert another property/value pair into the object.

game.price = 3000;
alert(game.price);

Play with the jsFiddle.

If you've been typing along in your Chrome console, you can type game (all by itself) into the console and hit ENTER to view the present contents of this object. The text Object with a right-facing arrow/triangle will appear when you do this and clicking the arrow will display the contents of game in a format similar to following:

title: 'Half-Life 2'
price: 3000
__proto__: Object

As you can see, game contains both pairs we have defined for it.

Don't worry about the __proto__. This refers to the object's prototype, which is nothing we need to worry about now.

So while we used the object literal syntax above, there is another way. The following lines are equivalent:

game = {};
game = new Object();

If you want to start off with an object literal containing multiple property/value pairs, you simply separate them with a ,.

game = {title:'Left 4 Dead', price:3000};

There is also another read/write syntax.

The following are equivalent for reading values for a property:

game.title;
game['title'];

As these are equivalent for writing values for a property.

game.title = 'Portal';
game['title'] = 'Portal';

An important thing to note here is that the value can be of any type, but the property will always be a string. Even if you try to use something else, it will simply be converted to a string, as can be seen here:

game = {};
game[1] = 2;
game['1'] = 3;
alert(game[1]);

Play with the jsFiddle.

But if the properties are always strings, then why doesn't title have quotes in game.title or {title:'Left 4 Dead'}?

These are just shortcuts and are also taken to be strings. We've already looked at the case of the former, but in the case of the object literal, the following are equivalent:

game = {title:'Left 4 Dead'};
game = {'title':'Left 4 Dead'};

The first requires two fewer keystrokes, so you'll see me using that one more often than not.

Along with the rest of the world.

We can even attempt to access a property we haven't set yet:

game = {title:'Left 4 Dead'};
alert(game.description);

Play with the jsFiddle.

if we want to visit our good buddy undefined.

And remember: the value stored in a pair can be of any type.

This includes functions, as shown here:

gundam = {};
gundam.shoot = function(){ alert('pew pew pew!') };
gundam.shoot();

Play with the jsFiddle.

See also: Gundam

It should also be noted here that gundam.shoot() is properly known as a method call. As is the case with the terms "parameter" and "argument", here too you will often find "function" and "method" used interchangeably.

That said, a function belonging to an object is a method.

this

We're going to mix a little of what we've just learned and explore this.

"Who's on first?"

We... never mind.

There is no shortage of references and blog posts covering the ins and outs of this, so I highly encourage you to go on to read those later, but I will happily give you my own expedient tour.

Consider yourself disclaimed.

The keyword this represents the value of the current context. To start off, we need to acknowledge the existence of the global context (or global scope), which is the all-encompassing context in which the JS program is executed.

As proof, let's show a redundant use of this using a very simple program.

alert(this.property);
property = "value";
alert(this.property);

Play with the jsFiddle.

See how we didn't prefix the property declaration with this., yet it was still accessible using this.property? That's because property was declared in the global context (as opposed to being defined within a function).

You'll also notice that if you just type this into the console and hit ENTER, that it is an object known simply as Window. When JavaScript is executed in the browser, the global object is the window (or more specifically in the case of Chrome, the tab) that it is executed in. You can also access the global object anytime by using the special variable window.

this acts differently when used inside of a function or method, but we'll see that later.

We need some additional knowledge before these concepts become particularly useful to us, but they will reveal themselves to be of critical importance when we start talking about the DOM and jQuery.

One last note on JavaScript objects: in many ways they look and act like what are known elsewhere as hashes or associative arrays.

Later on, we will see a similar {} and [] syntax used for Ruby hashes as what we've seen used here for JavaScript objects.

And it will be glorious.

Booleans and Conditionals

Okay, so we've looked at a fair amount of JavaScript at this point, but how do we "make decisions" (so to speak) in JavaScript?

So far we've only written code that will run indiscriminately, but what if we want certain code to run only when certain conditions are met?

Well, for that we would need a conditional. More specifically, we'd need an if statement.

Conditionals are used to execute a section of code only if and only if its condition are true.

So what is "true"?

Well, JavaScript provides a type for this very case: boolean. There are only two boolean values: true and false. Logical, right?

In case you're unfamiliar, the term "boolean" is used throughout computer science to refer to a true or false value and is named after George Boole.

Let's jump into conditionals and booleans with a contrived example!

if(true){
  alert('This will run because the if check passes.');
}

if(false){
  alert("You'll never see this because the if check fails.");
}

Play with the jsFiddle.

The {} and its contents is referred to as a code block or, more simply, a block. The code block is only executed in the event that the if statement preceding it passes.

Okay, the example makes sense, but are we always going to be passing around true and false like that?

Not usually. Typically we're going to be using comparison operators, and perhaps some logical operators along with them, to create a boolean.

That's the terminology at least. Basically, we'll just be comparing a couple things or a series of things to get a true or false.

Usually.

Let's see an example. We're also going to make use of another new keyword named else that works in conjunction with if exactly as you'd expect it to by its name.

alertPositiveOrNegative = function(num){
  if(num < 0){
    alert("NEGATIVE");
  } else {
    alert("POSITIVE");
  }
}

Play with the jsFiddle.

We can pass that function any negative number and it will alert "NEGATIVE". Pass it any positive number and it will alert "POSITIVE".

Equivalently, we could have used the ternary operator (?:) to perform the check like this: num < 0 ? alert("NEGATIVE") : alert("POSITIVE");.

Sometimes using a ternary operator is cleaner, sometimes it's not. You get to decide.

Awesome!

But there's a problem here, because there is an exception to negative and positive, and its name is "zero".

To fix our function to handle the case of zero, we'll throw in another check, but this time we'll have to pair up our two new keywords into else if.

alertPositiveOrNegative = function(num){
  if(num == 0) {
    alert("ZERO");
  } else if(num > 0) {
    alert("POSITIVE");
  } else {
    alert("NEGATIVE");
  }
}

Play with the jsFiddle.

There. Now it supports zero as well.

Notice here that the comparison operator to test for equality is == and not =. The reason for this is simple: = is already used for assigning values to variables.

Another thing you may have noticed is that the last else is all by itself without an if. Logically, we should be good with our previous scenario of positive and negative numbers as well as zero, but what happens if we pass in a string? Think about it and then give it a try.

Spoiler alert (no pun intended), we get "NEGATIVE".

Obviously, a string cannot be negative, but it simply fell through to the final else that doesn't perform any checks. The lone else executes its block in the event that all the if statements above it fail.

This problem is, of course, quite easy to rectify:

alertPositiveOrNegative = function(num){
  if(num == 0) {
    alert("ZERO");
  } else if(num > 0) {
    alert("POSITIVE");
  } else if(num < 0){
    alert("NEGATIVE");
  }
}

Play with the jsFiddle.

Now if we pass in a string, we won't get any alert at all. Good enough.

But...

"What now!?"

Comparison

There's one bit of JavaScript strangeness here that you should be aware of. To see what I'm talking about, try passing '1', '-1', or '0' into alertPositiveOrNegative. You'll get an alert.

Play with the jsFiddle.

What in the world?

For better or worse, the JavaScript comparison operators we're using will do some approximating.

Try running the following in the console to see that they all return true:

2 == 2;
'2' == '2';

2 == '2';
'2' == 2;

2 < 3;
2 < '3';
'2' < '3';

As you can see here, we have a "less than" comparison operator available to us as <. There is also a >, <=, and >= ("greater than", "less than or equal to", and "greater than or equal to" respectively).

One way we can avoid this comparison operator weirdness is to use the === operator instead of ==, because it will make sure that the values are exactly the same.

See for yourself:

2 === 2;
2 === '2';

And if we want to test to see if things are different, we can use the != and !== operators which are the logical opposites of their respective == and === counterparts.

2 !== 2;
2 !== 0;

Because of the type approximation of == and !=, it is strongly recommended that you always use === and !==. If you have a good reason not to, that's fine, but you're taking your life into your hands.

And ! is also an operator unto itself, read as "not". The following will both return true:

true  === !false;
false === !true;

Truthy, Falsy, and the Elicited Boolean

Though the absolute truth of booleans is nice, sometimes we won't really care to check an actual boolean and will just use regular values in our if checks.

An excellent example of this is if we want to see if something is defined. Imagine we only want to alert(str) if str is defined.

if(str) alert(str);

var str = 'hey';

if(str) alert(str);

Play with the jsFiddle.

This will result in only one alert, because str is undefined during the first if check.

So how does an if test a non-boolean value?

We can use non-boolean values for if's because all values in JavaScript are either truthy or falsy, meaning that they are treated as either true or false, respectively, when used where a boolean is expected.

The list of falsy values is as follows:

  • false
  • undefined
  • ""
  • 0
  • null
  • NaN

We haven't discussed those last two yet. ...but they are falsy.

Everything else is truthy.

To prove this in the console, we can elicit a boolean from any value with a leading !!, a double "not". This works by "notting" the truthiness of the value into a proper boolean and then "notting" that into the boolean form of its truthiness.

The following will all be true:

!!1  
!!-1

!!"foo"
!!"bar"

!!0  === false
!!"" === false

And these will be false:

!!0
!!""
!!NaN
!!null
!!undefined

We could also use Boolean(someValue) to get a boolean, but that would just be more typing.

while and switch

Another language feature that also checks for truthiness is while.

num = 1;
while(num < 6) {
  alert(num);
  num += 1;
}

Play with the jsFiddle.

This code will alert the numbers 1 through 5.

We start by setting a value to num and then create a while check that reads as "while num is less than 6". This code will loop and continue to execute the code block as long as that check is true.

Inside we alert the value of num and increment num with num += 1 for each pass through the loop.

We can also break out of the loop with the break keyword.

 
while(true) {
  break;
  alert('this line will never run');
}

Play with the jsFiddle.

Be careful doing while(true), because without any way to break out of this kind of loop it is what is known as an "infinite loop" and it will run forever.

There may be cases where this is what you want, but more often than not you won't and it'll just end up cranking your CPU to 100% and making your laptop fan run really hard.

Switch statements are another instance of something that operates on booleans. They look like this:

str = 'Animal'

switch(str){
  case('Animal'):
    alert('case for animal!');
    break;
  case('Plant'):
    alert('case for plant!');
    break;
  default:
    alert('no cases matched!');
}

Play with the jsFiddle.

Be sure to note of the break's that get thrown in each of the case's. The reason they're there is that without them, execution would just keep flowing down into the next case.

Personally, I don't see these a whole lot, but when they're appropriate, they're very useful.

null and NaN

null and NaN are two special JavaScript values that we've heard are falsy, but haven't learned about yet.

null is similar to undefined in that it basically means "nothing here", except that the fact that the value of a variable is null implies that that variable is defined, rather than undefined. A subtle difference, yes, but one that exists in JavaScript.

NaN is ridiculous and poisonous. It's poisonous in that it poisons every number it touches, turning the result into NaN itself.

It's ridiculous in that it's terrible.

"NaN" stands for "Not a Number" and we will find it whenever we try to typecast something to a number when it isn't (e.g. Number('foo')).

Try the following in the console:

!!NaN

Number('foo');
NaN + 1
NaN + 'foo'

NaN === NaN

Also, as you can see from executing the last line, NaN isn't equal to anything, even itself.

If you figure that one out, let the world know.

Arrays

So we've already talked about objects, which can be used to hold property/value pairs, but sometimes we just want a data structure that holds a bunch of values in a particular order; sometimes we want an array.

Let's make and play with one:

arr = [1,2];

arr[0] === 1;
arr[1] === 2;
arr.length === 2;

arr[2] = 3;

arr[2] === 3;

arr.length === 3;

Play with the jsFiddle.

The most important thing to remember about arrays is that they use zero-based indexing. This means that the "first" element of an array is actually the zeroth element of that array, meaning its index is 0 and not 1.

Above, arr[0] can be read in English as "arr sub zero" and retrieves "the element of arr at index 0".

JavaScript arrays have a number of methods like the ones we'll soon see that Ruby has, like .push, .pop, .shift, .unshift, .split, and .join. Keep and eye for an explanation for these in the Ruby chapter.

For Loops

Frequently, you'll want to loop through every element in an array and do something to it or with it. One way to do this is with a for statement, like this:

arr = [1,2,3]

for(var i = 0; i < arr.length; i += 1){
  alert(arr[i]);
}

Play with the jsFiddle.

Inside the () for the for, there are three parts defined. First, an iterator variable (var i = 0) , then a condition (i < arr.length), and finally a line to be executed after each iteration (i += 1).

Though the for statement is important to understand, using jQuery's .each instead for this is much easier.

There is also a for ... in syntax, but as it has some quirks. Again, I'll point you to jQuery.each.

Comments

JavaScript also offers comments.

// this is a comment

/*

these
lines
are
also
comments

*/

// these
// lines
// are
// also
// comments
// too!

The block comments (shown second) might seem more useful, but because of the way many text editors comment out lines, many people comment out series of lines with a series of inline comments (as show third/last).

console.log

Often times, we'll want to print a lot of information to debug our code and a bunch of a alert's would just be a pain.

alert is also blocking, meaning it stops execution until it's done (i.e. the alert is closed).

Fortunately, we can output values instead to the console way using console.log.

Try the following in the console to check it out:

console.log('hi!');

console.log(1, 2, 3);

console.log({foo:'bar'});

HTML onclick

I thought we were talking about JavaScript...

Well, this is a topic that doesn't make any sense without an understanding of JavaScript, so we held off.

The onclick attribute is used to execute JavaScript upon a click event for an element.

Here's an example of a link that will alert when clicked:

And here's its markup:

<input type="button" onclick="alert('You clicked me!');" value="Click me" />

Now given we had the following JavaScript (and it was executed in the global context):

clickAlert = function(){ alert('You clicked me!') };

then we could also do the following :

<input type="button" onclick="clickAlert()" value="Click me" />

Play with the jsFiddle.

The DOM

"DOM" stands for "Document Object Model" and is an object representation of the elements of an HTML, XHTML, or XML document and allows for programmatic manipulation of the HTML of the page in the browser with JavaScript. Any changes to the page after page load are accomplished using some variation of the technique shown below.

We'll look more at the term "page load" during the wrap up.

To see how we can manipulate the DOM, let's create a button and change its value when it's clicked using JavaScript.

<input id="foo" type="button" value="Foo" onclick="document.getElementById('foo').setAttribute('value','Bar');" />

Clicking the button that this markup creates will cause the onclick JavaScript to be run. This JavaScript searches the HTML document for an element with an id of foo (the button itself) using document.getElementById('foo'). The resulting element from that call then has .setAttribute('value','Bar') called on it, which changes the display value of the button by changing its value attribute.

Notice here that our document.getElementById('foo').setAttribute('value','Bar'); call takes the form foo.bar().baz().

In foo.bar().baz(), we call .bar() on foo and then call .baz() on the return of foo.bar(). This is called method chaining and becomes very useful, most especially in jQuery.

If the JavaScript in the onclick looks like an unnecessarily verbose way to accomplish this, you'll be glad to know that jQuery works to abbreviate this process for us (as we'll see very shortly).

Also, this practice of manipulating the markup of a page (and its styling) using the DOM and a scripting language is referred to as "DHTML", which stands for "Dynamic HTML" because it allows us to dynamically (after page load) change the page by changing the HTML.

Honestly, I heard this term long after I was already "writing DHTML" (and professionally). Don't know if this is the case everywhere, but the term "DHTML" does not get used much in my circles.

This may be due to the fact that it's less "DHTML" and more "just the way we do things now" at this point.

Events

You may have noticed the wording earlier for onclick included something about a "click event". We'll be seeing more on this later on when we talk about jQuery and we build our application, but for now understand that DOM elements can have events fired on them and that we can bind callbacks/handlers to those events, which allows us to choose how to respond (i.e. what JavaScript to execute).

Miscellaneous

First, a note from above. typeof is actually an operator and doesn't need the ()'s, but we used them above anyway.

And then there are also Some other JavaScript topics worth looking into:

  • try/catch
  • setTimeout()/setInterval()
  • the .call and .apply methods
  • the use of arguments within a function
  • Regular Expressions (we'll talk about these later for Ruby)
  • JavaScript classes and prototypes

These things and much, much more are covered in the JavaScript videos linked to in the resources page.

2.3.1 | jQuery

As we saw earlier, manipulating the DOM with JavaScript offers up some interesting possibilities, but the amount of code it takes to accomplish even basic tasks this can be a pain to type out. More importantly though, it can also act differently depending on what browser the code is run in. If this sounds like an awful problem it is. ...was.

Developers took note of this and set out creating various JavaScript libraries such as jQuery, MooTools, Prototype, script.aculo.us, and Zepto to help out with these problem (and more). All of these are written in JavaScript, so none of them are languages themselves, they simply add functionality to the language.

Hence the term "library".

jQuery specifically has grown to be quite popular and was adopted by Rails as of version 3.1 (Rails had used script.aculo.us by default prior to this). Looking around at the other libraries available after you'v e gotten the hang of jQuery is definitely encouraged, but jQuery is quite solid, as it is used everywhere, and does a really great job. Better yet, it plays nice with Rails, right out of the box.

$

You can't really get anywhere in jQuery without the $ variable.

What does it do?

Well, remember that document.getElementById('foo') from our DOM example earlier? The one we used to get an element with an id of foo?

Here's the jQuery equivalent:

$('#foo')

Wasn't that easy?

$ is actually just an alias for the jQuery variable, but you'll probably see $ more often. ...because it's shorter and people are lazy.

Other JavaScript libraries also use the $ though, so if you ever run into problems with this, check out jQuery.noConflict.

Well, this short line of jQuery may be short, but it can still seem a little confusing. To figure out what exactly is going on here, let's take a deeper look at $.

First of all, remember that $ is a valid character for use in JavaScript variable names and can, as seen here, even stand alone as a variable name.

Furthermore, we know that variables can hold functions and that's exactly what's happening here. So what we did above is just a normal function call, specifically $().

And finally, we're passing that $ function a single argument, the string '#foo'. Look familiar? That's right, it's a CSS selector string that would read as "the element with the id of foo".

These selectors will work in jQuery to indicate particular elements just the same as they would in CSS. In fact, they can do even more.

Okay, so, I sort of lied again.

ಠ_ಠ

$('#foo') is not the exact equivalent of the document.getElementById that we saw before, and for a couple of reasons.

First of all, it does not return the single DOM element, even though we are a asking in this case for an element by id which implies that we are looking for a single element. Instead, it returns an array-like object. In this case, it contains only one value: the element we're looking for. The reason this returns an array regardless is that the syntax is ambiguous; we pass it a string representation of a CSS selector and could be asking for one or many elements.

Fortunately, we can treat the return from $(...) as a single object and call things on it like it isn't an array.

How does it know?

I dunno, but I bet the source does.

The other difference is that our call to $ returns a jQuery object rather than a DOM object. This difference is fairly subtle, since they can be used to do similar things, but ultimately jQuery methods can only be called on jQuery objects, not on DOM objects.

In fact, if you ever find yourself with a DOM object in, say, a variable named obj, you can easily convert it to a jQuery object by using $(), like so: $(obj).

For instance, later on when we're building our application, we'll want to call the jQuery method .scrollTop on the window object, but since it's not a jQuery object, we can't simply call window.scrollTop(...). We can however, pass window into $, get its equivalent jQuery object in return, and call .scrollTop on that, like this: $(window).scrollTop(...).

So, going back to CSS selectors in jQuery, just as with regular CSS selectors, we can also indicate the type of element we want with $('div') (all <div>'s in the document) or all elements of class some-class with $('.some-class'). Cases like these are exactly the reason that $(...) will return an array-like object, because it is possible that we are expecting several elements.

Additionally, we can use CSS psuedo-classes as jQuery filters, like :first-child:

chap1 = $('#chapter-list:first-child');

And we can even specify what attribute values we want our matches to have. Let's say we had a bunch of <input>'s, but we only wanted those with type="text":

$('#our-form input[type="text"]');

So there you have it, we're off and running in jQuery!

Contents

So let's say we have this somewhere on the page:

<p id="p1">Some text.</p> 

How would we grab "Some text." out of that element and into a JS variable?

Piece of cake:

var text = $('#p1').text();

Play with the jsFiddle.

Note that this is the function call .text() and not just the property .text.

And if we wanted to change the contents of that same <p>?

$('#p1').text('Boom!');

Play with the jsFiddle.

You should be sure to keep in mind that here text indicates literal text, meaning that whatever you dump in will not be treated as HTML. Let's see an example that illustrates this.

$('#p1').text('<a href="#">link to nowhere</a>');

Play with the jsFiddle.

The above results in a <p> containing the text we passed as an argument rather than an anchor tag.

To have the argument interpreted as HTML, we simply pass it to a different function:

$('#p1').html('<a href="#">link to nowhere</a>');

Play with the jsFiddle.

This example, using .html(), actually creates an <a> element inside the <p> like we were aiming to do.

One last note about these methods: when using them to assign content to an element, they will completely blow away whatever previously existed and replace it with the value of the passed argument.

As you might imagine, this is not always what we would want to do, and so there are a number of other methods to help us keep what we want.

Creating Elements

Passing a string to .html() is certainly not our only means of adding elements to the page. To start looking at our options, let's look at another way of creating elements.

var el = $('<a href="#">link to nowhere</a>');

Now HTML strings are getting passed into $() too?

$ actually serves multiple purposes and can properly handle both roles, treating different strings appropriately (e.g. creating an element when passed text representing HTML, searching for elements when passed a CSS selector string).

How does it know?

For an answer to that, you should absolutely check out the jQuery source!

Oh, and el is an ultra ugly abbreviation for "element" that you might see used under circumstances like this. Some people I've worked with have been disgusted by my use of it, but I challenge you to find anything equally short that makes sense.

Now, what we've done here is create a new element which is stored in memory with JavaScript as el but unattached to the DOM; it's just floating in space.

And by "space" I of course mean "(computer) memory", as distinctly different from being displayed on the page.

There are a boatload of methods to place the element into the DOM before or after a given element or elements, but let's just assume that we want to place our new <a> after everything inside of #p1. To accomplish this, we'll use .append, like so:

$('#p1').append(el);

Play with the jsFiddle.

We could even do the whole thing inline:

$('#p1').append($('<a href="#">link to nowhere</a>'));

but personally I try not to run a ton of special characters together like ($(' (after .append above), so I tend to assign things to variables. In this kind of situation I think it helps to keep track of what exactly I'm passing around.

In short, I like to make what I'm actually doing as clear as possible.

We could also blast away the contents of #p1 entirely and add el:

$('#p1').empty();
$('#p1').append(el);

Play with the jsFiddle.

This will actually yield the same result as the .html('<a>...') earlier.

If we wanted to blow away the contents of #p1, couldn't we just do $('#p1').text('');?

We absolutely could, but .empty() is more declarative, it states its purpose clearly, so I tend to use it in circumstances like these.

There is also a .prepend, a .before, an .after, an .insertBefore, and an .insertAfter which all work as you think they would.

Most of the time when I find myself wondering "Is there a jQuery function for [FILL IN THE BLANK]?", there is; so don't hesitate to google around if you find yourself thinking the same way.

A final important note on these kinds of methods: if you call them on multiple elements, they will add multiple elements.

What does that look like?

Say we have two empty <div>'s of the same class:

<div class="same"></div>
<div class="same"></div>

and we do this:

var el = $('<p>TEST</p>');
$('.same').append(el);

Play with the jsFiddle.

What do you think we get?

Both <div>'s will now have a child <p>.

Potentially not what we want, so be careful.

Oh, and one more thing. There's a really handy syntax for jQuery element creation that uses a JavaScript object literal to define attributes and content:

var el = $('<a>', {
  'class': 'foo bar',
  href: '#',
  text: 'link to nowhere'
});

We could even take this a step further and define the object first and pass it in:

var attrs = {
  'class': 'foo bar',
  href: '#',
  text: 'link to nowhere'
};
var el = $('<a>', attrs);

Play with the jsFiddle.

This is equivalent to var el = $('<a class="foo bar" href="#">link to nowhere</a>'); but is, in my opinion, more readable. If you find yourself writing a long string representation of an element with a ton of attributes, this might be a nice alternative to help those that follow to make sense of your work.

Note the quoted string 'class' as the property in the object literal. This is necessary because class is a reserved word in JavaScript and this is the only way to use 'class' as a key here.

Attributes

jQuery also makes it easy to fetch and adjust attributes of existing elements with the .attr() method.

So let's say we had the following anchor in a page:

<a id="link" href="#">link to nowhere</a>

If we wanted its href value, we'd could grab it with .attr():

var href = el.attr('href');

Play with the jsFiddle.

If we wanted to change the href to something else, we could do that with .attr() as well:

el.attr('href', '/some/path');

Play with the jsFiddle.

And we'd be left with the markup:

<a href="/some/path">link to nowhere</a>

So both reading and setting elements' attributes are accomplished with .attr(), the difference being that reading takes one argument and setting takes two.

We can even change the id of #link:

$('#link').attr('id','zelda');

Play with the jsFiddle.

and change it back:

$('#zelda').attr('id','link');

In fact, we can change any kind of attribute, including class:

$('#link').attr('class','hylian');

Play with the jsFiddle.

But what if we want to just add another class to the element? If we did another .attr('class', '...'), we'd hose what was already there.

We could grab the present value, concatenate the new class string, and set that whole thing as the new string for class. ...but that would be a complete waste of time for so common a task.

Luckily there's another way.

Changing Classes

If we wanted to add the class triforce-courage to #link from above, all we'd need was a call to .addClass():

$('#link').addClass('triforce-courage');

Play with the jsFiddle.

This would result in:

<a id="link" class="hylian triforce-courage" ...</a>

Perfect.

And if we wanted to get rid of the hylian class?

Easy, that would be the job of .removeClass:

$('#link').removeClass('hylian');

Play with the jsFiddle.

There's even a .toggleClass that will add the class if it isn't on the element or remove it if it is.

And keep in mind that these methods will work for multiple elements, so if $ returns multiple elements and we call .addClass('foo') on the return, then all of those elements will have a 'foo' class added to them.

In case you're wondering why we would want to add and remove classes like this in the first place, it's because we often use CSS in combination with JS/jQuery to hide, show, highlight, or otherwise change an element.

For instance, there could be a CSS style like .hidden { display: none; } which we are using to hide certain elements. If we want el to disappear, we can just add the hidden class to get it gone like so el.addClass('hidden').

Events

We talked a little about events earlier, during our overview of JavaScript, but jQuery makes it easier to take a deeper look.

You'll remember that events are fired or triggered for certain elements when various actions occur for/on them. Furthermore, we can bind to those events to run specific code in reaction.

With jQuery it's ridiculously easy to bind to a particular event. Let's say we want to bind to the click event for our good buddy #link and make an alert().

Without further ado:

$('#link').bind('click', function(event){
  event.preventDefault();
  alert('Clicked!');
});

Play with the jsFiddle.

In fact, doing this is so common that there is also a .click method to accomplish the same thing. So we could have equivalently done:

$('#link').click(function(event){
  event.preventDefault();
  alert('Clicked!');
});

But there are many, many more events, so let's just focus on .bind for now.

Okay, first of all we see that we are calling the .bind method on $('#link').

Secondly, we are passing .bind two arguments. The first argument is a string, 'click', which is the name of the event we wish to bind to. The second is an anonymous function that in this context is referred to as a callback function or handler. This is the function that will be executed when the event we're binding to is fired.

Lastly, the callback has one parameter: event. There are a number of things that we can do with this, but the most relevant one right now is to stop the browser from following the link (the default functionality for a link) and simply execute our code instead. This is accomplished by calling the .preventDefault method on event.

Our href isn't anything important here, but regardless, we don't want the default functionality.

After that, we just alert() our message like we wanted to!

It's also worth pointing out that the second argument that we pass to .bind needs only to be a function, it doesn't necessarily have to be an anonymous one.

Thus, the following is equivalent to what we have above:

var callback = function(event) {
  event.preventDefault();
  alert('Clicked!');
};

$('#link').bind('click', callback);

Play with the jsFiddle.

A very important thing to notice here is that we pass the function itself as an argument as callback, not callback(). The latter would attempt to run the function (and subsequently throw an error because we didn't pass it an event) which is not what we want. What we want is to pass in a function to be run later so that it can be run later when the event is triggered for the element.

Speaking of triggering events, we can actually force this with jQuery too. We can, for instance, trigger a click event on a link, even though the link was never actually clicked by the user. This is an easy way to emulate a user action or run code that you know you have stored in a callback for a particular element/event.

This is how we do it:

$('#link').trigger('click');

Play with the jsFiddle.

And just as we bind to events, we can also unbind:

$('#link').unbind('click');

Play with the jsFiddle.

This will unbind the callback function we assigned earlier for the click event.

We can even go even further and unbind all events with $('#link').unbind(); (passing no arguments).

Now, while .bind and .unbind are great, they have one pitfall: they only work for elements that exist in the page when they are run.

This seems like a bit of a no-brainer, but remember that we are dynamically adding elements to a page. Often times, you may not have all the elements of a particular class in the page yet, but you do want them to all act the same way once they get there.

In order to make this happen we can use .live and .die.

To demonstrate these methods, let's say we have an empty element like this:

<div id="container"></div>

We anticipate that this <div> will contain <a> elements and want them all to alert instead of acting as a means of navigation like what we saw above. Assuming callback is still defined for us, we can accomplish this with .live like so:

$('#container a').live('click', callback);

Now, even though no such elements were even present when that JS was run, we can add an anchor element:

var a = $('<a>', {href:'#', text:'dynamically added link', 'class':'link'});
$('#container').append(a);

Play with the jsFiddle.

and when we click the link we've just added to the page, it will alert.

As you might expect, .die is used to unbind events bound using .live. We can remove the binding from .live(...) with $('#container a').die('click');.

There's a ton of other stuff in jQuery Events worth looking at, but we won't be touching on that here.

Above and Below

Now what if we had the following HTML:

<div id="top">
  <p id="middle">
    <a id="bottom" href="#">some text</a>
    <a href="#">some other more text</a>
  </p>
</div>

and let's say we've run the following JS:

top    = $('#top');
middle = $('#middle');
bottom = $('#bottom');

How then would we be able to get at middle's child elements? Or its parent?

Children: middle.children();

Parent: middle.parent();

Play with the jsFiddle.

.children will also accept a CSS selector. If we strictly wanted all of the child <p> elements, we could have used middle.children('p'); above.

Furthermore, if wanted to find all of the <p> underneath top, we could use top.find('p'). From this, we can see that the .find method works not just for children, but for descendants in general.

Inversely, if we wanted to look for ancestors, we could use .parents() or .closest(), as in bottom.closest('div');.

.index()

And if we wanted to figure out the (zero-based) index of an element, we can use the .index() method.

Assuming we still have the markup from above, we can get the index of p#bottom relative to its siblings with:

$('#bottom').index();

Notice that we don't have to pass any arguments into the method call here since the element's index is determined by its relation to its siblings.

Play with the jsFiddle.

.each()

Remember how I said that there was a feature of jQuery that was easier to use than the native JavaScript for?

Well this is it: .each.

Let's say we wanted (for some crazy reason) to empty all of the paragraph elements in a page. We could accomplish this using .each:

$('p').each(function(){
  $(this).empty();
});

Play with the jsFiddle.

To do this, we call .each on a jQuery object and pass in an anonymous function that should be executed for each element therein.

In the case above, we will want to call .empty() on each element. Within the callback, we can access the element currently being iterated over with this. But since this is a DOM object, we need to call $(this) to convert it into a jQuery object.

There are a couple other uses for .each. Try running the code below in the console to loop through a standard JavaScript array.

$([1,2,3]).each(function(i, obj){
  console.log(i, obj);
});

$.each([1,2,3], function(i, obj){
  console.log(i, obj);
});

As seen here, we can also name two parameters for our .each() function. The first is the index of the current iteration (base zero) and the second is the current object for the iteration.

Animations

There are a number of jQuery methods that involve animations, like .show and .hide, which do exactly what they sound like they'd do, but there is also an .animate() method to animate all kinds of things.

We won't be looking any deeper at these, but if you see anything animating on our pages later, this is how it's done.

2.4 | Wrap up

Now that we've looked at all the common web languages, we need to figure out how they fit together.

Traditionally, CSS and JS were both included in the <head> of their HTML documents, but lately that has changed as more and more people are opting to throw their JavaScript at the end of the <body> for faster load times.

This works because by allowing the HTML to be mostly parsed and the styling mostly applied before any scripts are requested or run.

Having given that a nod, we're going to look at some traditional examples of how to add CSS and JS to an HTML document.

First, we can add inline CSS and JS into HTML using <style> and <script> elements, respectively, like so:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML with CSS and JS</title>
    <style type="text/css">body{color:blue;}</style>
    <script type="text/javascript">alert("Hello, World!");</script>
  </head>
  <body>
    <p>Example text.</p>
  </body>
</html>

Play with the jsFiddle.

As we can see, the text content of a <style> element is treated as CSS and the text content of a <script> element is executed as JavaScript.

The above example will work, but typically you'll want to keep your CSS and JS in separate files and reference them in your HTML with <link> and <script> elements, respectively.

Be sure not to confuse <link> with <a>.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML with CSS and JS</title>
    <link type="text/css" src="/stylesheets/styles.css" />
    <script type="text/javascript" src="/javascripts/application.js"></script>
  </head>
  <body>
    <p>Example text.</p>
  </body>
</html>

Assuming the paths are correct and have the same content as above, this would be an equivalent implementation.

Notice is that CSS has the extension .css and JavaScript has .js.

There is a difference with this implementation though, and that is that the CSS and JS files will need to be fetched via their own HTTP requests. As developers, we don't need to do anything else to get them fetched or run within the browser, but it's important to know that they won't end up baked into the HTML this way.

We can still find them in Dev Tools though, this time under the Stylesheets and Scripts pills for the Network tab.

Also, images are fetched via their own HTTP requests as well.

We can even include scripts from other domains in our page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

But be very careful doing this, only use scripts from sources you absolutely trust.

This is discussed further in the security section.

Page Load

We've seen the term "page load" several times now, but what does it mean?

To a developer "page load" refers to the state when all of the assets (e.g. HTML, CSS, JS, images) for the page have been successfully fetched (via HTTP) and all scripts have been executed. In short, the point at which the page has settled.

This is exactly the point in time when we can assume that all the JS we've written and added to the page has been run.

The problem is that we might have our JavaScript spread across multiple files and we may not know exactly what order we've included them in the page. Since the browser fetches and runs scripts in order, top to bottom of the HTML, we might define a function in one file and be expecting to be able to call it in another, only to get an error because the call was made before the function was defined.

To fix this, we could use window.onload or <body onload="..."> (like the developers of old) to register a function to run when the load event fires on window, but what we really want is to run our code when the DOM is ready. jQuery offers a clean solution to accomplish this:

$(function(){
  // code in here will run
  // after page load
});

// the above is equivalent to:
$.ready(function(){
  // code in here will run
  // after page load
});

We can pass a function into $() or $.ready() and it will be executed after page load.

We'll be using this later on as we build our application.

Browser Compatibility

One final but important note to add to all of this is that not all browsers treat these languages the same.

In fact, Internet Explorer 7 and lower are notoriously terrible.

For example, only the newest browsers support CSS3 (the latest version of CSS that includes features like box-shadow and border-radius).

...sadly.

There is no simple answer to this problem, but using jQuery and something like Modernizr is a good start.

Done!

Man, that was a lot of territory to cover. Excellent job making it through!

Now that we have an understanding of these languages, we'll be taking a break from code to look at a few more concepts before circling back to see more of jQuery when we talk about Ajax.

Next up: Computing Foundations!