24. JS, the Browser, and the DOM

In This Chapter

  • Learn how JavaScript and the rest of your page interact

  • Understand what the fuss about the Document Object Model (DOM) is all about

  • Figure out the fuzzy boundaries between HTML, CSS, and JavaScript

So far, we’ve looked at JavaScript in isolation. We learned a lot about its basic functionality, but we did so with little to no connection with how it ties to the real world—a world that is represented by your browser and swimming with little HTML tags and CSS styles. This chapter will serve as an introduction to this world, and subsequent chapters will dive in much deeper.

In the following sections, you will learn about the mysterious data structure and programming interface known as the Document Object Model (DOM). You’ll learn what it is, why it is useful, and how it ties in to everything that you’ll be doing in the future.

Onward!

What HTML, CSS, and JavaScript Do

Before we dive in and start answering the meaning of life...err, the DOM, let’s quickly look at some things you probably already know. For starters, the stuff you put into your HTML documents revolves around HTML, CSS, and JavaScript. We treat these three things as equal partners in building up what you see in your browser (Figure 24.1).

Image

FIGURE 24.1

A typical web page is made up of HTML, CSS, and JavaScript.

Each partner has an important role to play, and the role each one plays is very different.

HTML Defines the Structure

Your HTML defines the structure of your page and typically contains the content that you see:

<!DOCTYPE html>
<html>

<head>
  <meta content="sea otter, kid, stuff" name="keywords">
  <meta content="Sometimes, sea otters are awesome!"
name="description">
  <title>Example</title>
  <link href="foo.css" rel="stylesheet" />
</head>

<body>
  <div id="container">
    <img src="seaOtter.png" />

    <h1>What This Sea Otter Did to This Little Kid Will Make You
LOL!</h1>

    <p class="bodyText">
      Nulla tristique, justo eget semper viverra,
      massa arcu congue tortor, ut vehicula urna mi
      in lorem. Quisque aliquam molestie dui, at tempor
      turpis porttitor nec. Aenean id interdum urna.
      Curabitur mi ligula, hendrerit at semper sed,
      feugiat a nisi.
    </p>

    <div class="submitButton">
      more
    </div>
  </div>
  <script src="stuff.js"></script>
</body>

</html>

HTML by itself, kinda like Meg Griffin in Family Guy, is pretty boring. If you don’t know who Meg is and are too lazy to Google her, Figure 24.2 is an approximation of what she looks like.

Image

FIGURE 24.2

An artistic interpretation of Meg Griffin.

Anyway, you don’t want your HTML documents to be boring. To transform your content from something plain and drab to something appealing, you have CSS.

Prettify My World, CSS!

CSS is your primary styling language that allows you to give your HTML elements some much-needed aesthetic and layout appeal:

body {
  font-family: "Arial";
  background-color: #CCCFFF;
}
#container {
  margin-left: 30%;
}
#container img {
  padding: 20px;
}
#container h1 {
  font-size: 56px;
  font-weight: 500;
}
#container p.bodyText {
  font-size: 16px;
  line-height: 24px;
}
.submitButton {
  display: inline-block;
  border: 5px solid #669900;
  background-color: #7BB700;
  padding: 10px;
  width: 150px;
  font-weight: 800;
}

For the longest time, between HTML and CSS, you had everything you needed to create an awesome-looking and functioning page. You had structure and layout. You had navigation. You even had simple interactions such as mouseovers. Life was good.

It’s JavaScript Time!

For all the great things HTML and CSS had going for them, they were both limited in how much interactivity they provided. People wanted to do more on a web document than just passively sit back and observe what is going on. They wanted their web documents to do more. They wanted their documents to help them play with media; remember where they left off; do things with their mouse clicks, keyboard taps, and finger presses; use fancy navigation menus; see spiffy (yes, I used the word spiffy) programmatic animations; interact with their webcams/microphones; not require a page reload/navigation for any kind of action; and a whole lot more.

Image

It certainly helped that web developers and designers (aka you and me) were itching for a way to help create these kinds of things as well.

To fill in this gap between what HTML and CSS provided and what people wanted, you had third-party components like Java and Flash that thrived for many years. It wasn’t until recently that this trend changed. There were many technical and political reasons for this shift, but one reason was that JavaScript for many years just wasn’t ready. It didn’t have what it took either in the core language or in what browsers supported to be effective.

That’s no longer the case today. JavaScript is now a perfectly capable language that allows you to add the kinds of interactive things that people are looking for. All of these capabilities are accessed by the real star of all this, the DOM.

Meet the Document Object Model

What your browser displays is a web document. More specifically, to summarize the entirety of the previous sections, what you see is a collision of HTML, CSS, and JavaScript working together to create what gets shown. Digging one step deeper, under the covers, there is a hierarchical structure that your browser uses to make sense of everything going on.

This structure is known (again) as the Document Object Model. Friends just call it the DOM. Figure 24.3 shows a very simplified view of what the DOM for our earlier example would look like:

Image

FIGURE 24.3

Our DOM for all the HTML you saw earlier looks sorta like this!

Despite the simplicity, there are several things to drill in on that apply to all DOM structures in general. Your DOM is actually made up many kinds of things beyond just HTML elements. All of those things that make up your DOM are more generically known as nodes.

These nodes can be elements (which shouldn’t surprise you), attributes, text content, comments, document-related stuff, and various other things you simply never think about. That detail is important to someone, but that “someone” shouldn’t be you and me. Almost always, the only kind of node we will care about is the element kind because that is what we will be dealing with 99% of the time. At the boring/technical level, nodes still play a role in our element-centric view.

Every HTML element you want to access has a particular type associated with it, and all of these types extend from the Node base that makes up all nodes as shown in Figure 24.4.

Image

FIGURE 24.4

The arrangement of how the elements we typically see are structured.

Your HTML elements are at the end of a chain that starts with Node and continues with Element and HTMLElement before ending with a type (HTMLDivElement, HTMLHeadingElement, and so on) that matches the HTML element itself. The properties and methods you will see for manipulating HTML elements are introduced at some part of this chain.

Now, before we run toward using the DOM to modify HTML elements, let’s first talk about two special objects that get in the way before the road clears up for what we want to do.

The Window Object

In the browser, the root of your hierarchy is the window object that contains many properties and methods that help you work with your browser; see Figure 24.5.

Image

FIGURE 24.5

The window is a pretty big deal up in these here parts.

Some of the things you can do with the help of the window object include accessing the current URL, getting information about any frames in the page, using local storage, seeing information about your screen, fiddling with the scrollbar, setting the status bar text, and all sorts of things that are applicable to the container your web page is displayed in.

The Document Object

Now, we get to the document object highlighted in Figure 24.6. Here is where things get interesting, and it is also where you and I will be focusing a lot of our time.

Image

FIGURE 24.6

The document object is also sorta kinda a big deal.

The document object is the gateway to all the HTML elements that make up what gets shown. The thing to keep in mind (and one that makes more sense as we look at future chapters) is that the document object does not simply represent a read-only version of the HTML document. It is a two-way street where you can read as well as manipulate your document at will.

Any change you make to the DOM via JavaScript is reflected in what gets shown in the browser. This means you can dynamically add elements, remove them, move them around, modify attributes on them, set inline CSS styles, and perform all sorts of other shenanigans. Outside of the very basic HTML needed via a script tag to get some JavaScript to run in an HTML document, you can construct a fully functioning page using nothing but JavaScript if you felt like it. Used properly, this is a pretty powerful feature.

Another import aspect of the document object has to do with events. I will go into more detail on this shortly, but if you want to react to a mouse click/hover, checking a check box, detecting when a key was pressed, and so on, you will be relying on functionality the document object provides for listening to and reacting to events.

There are a few more big buckets of functionality the DOM provides, but I’ll highlight them as we get to them.

The Absolute Minimum

The DOM is the single most important piece of functionality you have for working with your HTML documents. It provides the missing link that ties your HTML and CSS with JavaScript. It also provides access one level up to your browser.

Now, knowing about the DOM is just part of the fun. Actually using its functionality to interact with your web document is the much larger and funner other part. When you are ready, turn (or flip) on over to the next chapter where we will go further.

If you have any questions about this or any other topic, post on the forums at https://forum.kirupa.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.203.172