Home > Sample chapters

What Is JavaScript?

Where JavaScript Fits

JavaScript plays a key role in modern application development, but JavaScript comes from humble beginnings. A common misconception that new JavaScript programmers (and many other people) have is that JavaScript is somehow related to the Java programming language. Here’s the first learning opportunity of this book: JavaScript is not related to Java. JavaScript was first built to enhance the web-browsing experience, but it’s grown well beyond the browser to become an important programming language in Microsoft Windows 8.

JavaScript programs are made up of text, just like the text that makes up a page of this book. The text for JavaScript programs is created in a certain order and placed within a certain area so that a web browser will do something with it. In much the same way, the text in this book is sequenced: right now, you’re reading this text, parsing its words, and producing results such as learning, validating your knowledge, or falling asleep.

In the world of computing, there is a model called client-server, where the client (think: web browser) requests resources (think: webpage) from a server, which is a different computer discoverable through a URL (Uniform Resource Locator, such as http://www.microsoft.com). When you request something from http://www.microsoft.com, your web browser is the client. It contacts the server for the webpage. The server sends the webpage (consisting of HTML, CSS, and JavaScript) back to the browser. The browser then shows, or renders, the page for your enjoyment.

The most common place that JavaScript runs is in the client web browser. This client-side execution should be differentiated from server-based languages such as C#, which run on the server. In the webpage example already discussed, the Microsoft site is likely running a server-based language such as Microsoft Visual Basic or C# to create the webpages. JavaScript also runs in desktop widgets (notably in Windows 8), in PDF documents, and in other similar places. This section explores how JavaScript interacts with other client languages to provide a rich application experience.

HTML, CSS, and JavaScript

The languages of front-end web development consist of HTML, CSS (Cascading Style Sheets), and JavaScript. HTML provides the descriptive elements that surround content to define the layout of the page. CSS provides the styling to make the marked-up content visually appealing. JavaScript provides the functional and behavioral aspects to both the content and the styling. These front-end languages are typically combined with back-end, server-side languages such as PHP, Visual Basic/C#, Java, or Python to create a full web application.

HTML

HTML is the language of the web. It’s the language developers use to create webpages. You can create working webpages and web applications with nothing more than just HTML; however, to today’s sophisticated users, such pages would be boring and look horrible—but they would be webpages nonetheless. HTML is a standard or specification (two terms that are used relatively interchangeably, in this case) defined by the World Wide Web Consortium (W3C). There are several iterations of the HTML specification. The most current is version 5, known simply as HTML5.

HTML consists of elements enclosed in angle brackets (< and >). You already saw examples of HTML elements in the first tutorial in the chapter. HTML elements, also called tags, describe the content they enclose and how that content should be rendered by the browser. For example, an HTML tag for an image element is <img>. When the browser’s rendering engine encounters that tag, it knows the contents of that tag should be a reference to an image file. Similarly, the <p> tag denotes a paragraph. Most tags, like <p>, also have a closing or matching tag used to denote the end of that element. In the case of <p>, the closing tag is </p>. Other tags use a similar syntax, with a forward-slash (/) used to denote the end of the tag.

Tags can contain other content, called attributes, within their angle brackets. Attributes provide additional information about the content. Some attributes are generic and can be used with all tags, while others are specific to particular elements, such as the <img> tag. For example, the <img> tag uses the src attribute to specify the location of the image file that the browser will load and render. Here’s an <img> tag that references an image called “SteveSuehring.jpg”:

<img src="SteveSuehring.jpg">

Pages that adhere to the HTML standard (and every page you write should adhere to the standard) have certain elements that appear in a certain order. First among these is the Document Type Declaration, or doctype. (See the related sidebar for more information.) The HTML5 doctype is used throughout this book and looks like this:

<!DOCTYPE html>

An opening <html> tag follows the doctype. This <html> tag is then followed by the page’s heading section. The heading section starts with a <head> tag and ends with the closing </head> tag. The <head> section is sort of a housekeeping area where information about the page itself is stored, such as the page’s title. Additionally, the <head> section is where you find references to other files the page uses, such as files containing Cascading Style Sheets (CSS), and files containing JavaScript. You might also find CSS and JavaScript code placed directly into this heading section rather than in other referenced files.

The body of the webpage follows the closing </head> tag. A page’s body begins with a <body> tag and ends with the corresponding </body> tag. Within the body of the webpage, you find the actual content, such as the text and images that make up what you see when you view the page in a browser. The HTML to identify or mark up that content is also contained in the body. JavaScript code can also appear within the body of a webpage.

After the closing </body> tag, the page itself is closed by the </html> closing tag that matches the <html> tag that opened the webpage, way back up on the top. Here’s a simple example that concisely shows you what I just spent five paragraphs explaining:

<!doctype html>
<html>
<head>
    <title>My Web Page</title>
</head>
<body>
    <div>My first content, in a div element</div>
</body>
</html>

Rendering this simple page in a browser results in a page similar to Figure 1-2.

Figure 1-2

Figure 1-2 A basic webpage.

CSS

HTML is frequently paired with CSS to help browsers deliver a visually appealing webpage. In essence, HTML describes the function of content, while CSS is responsible for providing the look and feel of that content. CSS enables page creators to define such things as colors, backgrounds (including background images), sizes of elements, and much more. For example, by adding some CSS to the previous HTML example, I can change the size and add a border to the <h1> element. The CSS code is shown here in bold:

<!doctype html>
<html>
<head>
    <title>My Web Page</title>
</head>
<body>
    <h1 style="border: 1px solid black; font-size: 0.8em;">My first content,
        in an h1 tag</h1>
</body>
</html>

The result is shown in Figure 1-3. You can find this code as basic.html in the companion content.

Figure 1-3

Figure 1-3 Applying a bit of style with CSS.

This example adds a border to the element and changes the font size. Both of these changes were accomplished using CSS properties. A CSS property is a style attribute you want to change, such as the color or font of an element. CSS operates via rules, where you select items and then apply style rules to those selected items.

The properties available are dependent on both the browser and on the element being changed.

The CSS in this example uses what’s known as an inline style to change the element on which the style is applied. An inline style is CSS written directly into a tag, and it’s perfectly OK to do that. However, it’s more typical to use styles placed in an external CSS file and referenced by your HTML page. You’ll see an example of external CSS later in this chapter. The main reason to use an external file is that CSS written for an element type can be applied across all elements of that type in a page. For example, if this page contained more than one <h1> tag, you could style all those in one sweeping line of CSS.

You can target CSS to only certain elements by using identifiers or ids. An id applies only to a single element on a page. CSS also uses the concept of classes. A class defines certain HTML elements that have common characteristics. For instance, you could create a class that includes only HTML elements in a certain section of a page. Collectively, tag names, ids, and class names are known as selectors. The essential syntax for CSS is as follows:

selector: { rule; }

Don’t worry if all of this seems a bit hard to understand at the moment. Both the HTML and CSS should come into focus as you progress through the book.

JavaScript

While HTML describes the function of content and CSS describes how to style that content, JavaScript is a programming language that’s responsible for much of the behavioral or interactive elements seen on webpages and in web applications. This includes everything from drag-and-drop form elements to navigational menus to sliders, spinning graphics, and other enhancements (and sometimes annoyances) on websites. JavaScript is also frequently used to provide immediate, client-side form validation to check for errors and show feedback to the user.

Deploying a website or web application is a mix of designer, usability, and developer skills. Design skills provide the look and feel of elements, usability skills ensure that the look and feel works for the way end users will interact with the site or application, and finally, development skills make all of it work. Of course, one person can have more than one of these skills, or a team of people working on a web project might be needed in order to cover all these skills. Because you are reading a development book, it’s safe for me to assume you want to learn or enhance that third web programming skill: development.

JavaScript in Windows 8

Until recently, JavaScript was used primarily for client-side web applications, but that’s changing. Windows 8 elevates JavaScript to a prominent role within the application development life cycle. For example, you can use JavaScript to create a fully functional application in Windows 8. These JavaScript programs have access to the file system and can interact with Windows itself through a library called Windows 8 Runtime (Windows RT). In other words, JavaScript is an equal partner in Windows 8 alongside more traditional application-level languages such as Visual Basic, C#, and so on. Much of JavaScript’s power in Windows 8 comes through another library, called WinJS, which this book will cover in detail in Chapter 8.

Placing JavaScript in a Webpage

The overall title for this section is Where JavaScript Fits, but so far I’ve discussed only the conceptual environment in which JavaScript operates. It’s time to fix that by discussing the literal location for JavaScript code on a webpage.

Just as you need to use an HTML <img> tag to inform the browser it should expect an image, you use the <script> tag to inform the browser it will be reading a script of some sort. There are a few different kinds or types of scripts web browsers can read; JavaScript is one of them.

You place JavaScript within the <head> or <body> section (or both) of an HTML document and you can place multiple scripts on a given page.

The browser executes JavaScript as it is encountered during the page-parsing process. This has practical implications for JavaScript developers. If your JavaScript program attempts to work with some elements of the HTML document before those elements have been loaded, the program will fail. For example, if you place JavaScript in the <head> section of a page and that code attempts to work with an HTML element that’s all the way down at the bottom of the page, the program might fail because the browser doesn’t yet have that element fully loaded. Unfortunately, the program will probably fail in subtle and difficult to troubleshoot ways; one time the program will work, and the next time it won’t. That happens because one time the browser will have loaded that HTML element by the time it executes the JavaScript code, but the next time it won’t. An even more fun (not really) failure scenario is when everything works in your local development environment on your computer but fails when deployed in real-world (and real slow network) conditions. One especially good method for solving this problem is with the jQuery ready() function, as you’ll see later.

The basis of JavaScript’s close coupling with a webpage is through the Document Object Model (DOM). Just as your perception of the elements on the page comes through a text editor or Visual Studio, the DOM represents the programmatic or browser view of the elements on a page. Much of what you do as a JavaScript programmer is work with the DOM. Unfortunately, the DOM works in slightly different ways depending on the web browser being used to render the page. Of course, if you’ve done any HTML and CSS work, you’re already familiar with the different and nuanced ways in which browsers render pages. The same is true for JavaScript. You’ll spend a nontrivial amount of time either writing for various browsers or troubleshooting why something isn’t working in a given browser.

For anything but the most basic scripts, you should use external JavaScript files. This has the advantage of providing reusability, ease of programming, and separation of HTML from programming logic. When using an external script (which is how most of this book’s examples will be constructed in later chapters), you use the src attribute of the <script> tag to point the browser at a particular JavaScript file, in much the same way you use the src attribute of an <img> tag to specify the location of an image in an HTML page. You’ll see how to specify external scripts in more detail later in this chapter, but here’s an example:

<script type="text/javascript" src="js/external.js"></script>

No JavaScript? No Problem.

Sometimes JavaScript isn’t available in your visitor’s web browser. The user might be using assistive technologies or maybe she just disabled JavaScript manually. Whatever the case, the <noscript> tag helps if JavaScript isn’t available in the browser. The <noscript> tag is used by most web browsers when scripting is unavailable. The content between the opening <noscript> and closing </noscript> tags displays for the user, typically informing the user (politely, of course) that JavaScript needs to be enabled in order for the site to function properly.