Lesson 19

Understanding Dynamic Websites and HTML5 Applications

What You’ll Learn in This Lesson:

  • Image How to conceptualize different types of dynamic content

  • Image How to include JavaScript in your HTML

  • Image How to display randomized text with JavaScript

  • Image How to change images by using JavaScript and user events

  • Image How to begin thinking ahead to putting all the pieces together to create HTML5 applications

The term dynamic refers to something active or something that motivates another person to become active. A dynamic website is one that incorporates interactivity into its functionality and design and that also motivates a user to take an action—read more, purchase a product, and so on. In this lesson, you’ll learn about the types of interactivity that can make a site dynamic, including information about both server-side and client-side scripting (as well as some practical examples of the latter).

You’ve had a brief introduction to client-side scripting in Lesson 4, “Understanding JavaScript,” and you used a little of it in Lesson 11, “Using CSS to Do More with Lists, Text, and Navigation,” when you used event attributes and JavaScript to change the styles of particular elements—which is referred to as manipulating the Document Object Model (DOM). You’ll do a bit more of that type of manipulation in this lesson. Specifically, after learning about the different technologies, you’ll use JavaScript to display a random quote upon page load, and you’ll swap images based on user interaction. Finally, having learned at least the keywords and the basic concepts involved in putting together the HTML, CSS, and JavaScript pieces, you’ll be introduced to the possibilities that exist when you’re creating HTML5 applications.

Understanding the Different Types of Scripting

In web development, two types of scripting exist: server side and client side. Both types of scripting—which is, in fact, a form of computer programming—are beyond the scope of these lessons. However, they are not too far beyond what these lessons cover. Two very useful and popular books in the Sams Teach Yourself series are natural extensions to these lessons: Sams Teach Yourself PHP, MySQL, and JavaScript All in One (for server-side scripting) and Sams Teach Yourself JavaScript in 24 Hours (for client-side scripting).

Server-side scripting refers to scripts that run on the web server, which then sends results to your web browser. If you have ever submitted a form at a website (which includes using a search engine), you have experienced the results of a server-side script. Some popular (and relatively easy-to-learn) server-side scripting languages include the following (to learn more, visit the websites listed):

On the other hand, client-side scripting refers to scripts that run within your web browser; no interaction with a web server is required for the scripts to run. By far the most popular client-side scripting language is JavaScript. Recent research has shown that more than 98% of all web browsers have JavaScript enabled. And with the exception of Opera Mini, mobile operating systems support between 90% and 98% of all JavaScript features.

Note

Despite its name, JavaScript is not a derivation of or even a close relative of the object-oriented programming language called Java. Released by Sun Microsystems in 1995, Java is closely related to the server-side scripting language JSP. JavaScript was created by Netscape Communications, also in 1995, and given the name to indicate a similarity in appearance to Java but not a direct connection with it.

This lesson and of course the rest of these lessons assume the use of JavaScript for client-side scripting; the coding examples in these lessons are all JavaScript. There are other scripting languages out there, but they are not used by most web developers.

Including JavaScript in HTML

JavaScript code can live in one of two places in your files:

  • Image In its own file with a .js extension

  • Image Directly in your HTML files

External files are often used for script libraries (code you can reuse throughout many pages), whereas code that appears directly in the HTML files tends to achieve functionality specific to those individual pages. Regardless of where your JavaScript lives, your browser learns of its existence through the use of the <script></script> tag pair.

When you store your JavaScript in external files, it is referenced in this manner:

<script src="/path/to/script.js"></script>

These <script></script> tags are typically placed between the <head></head> tags because, strictly speaking, they are not content that belongs in the <body> of the page. Instead, the <script> tag makes available a set of JavaScript functions or other information that the rest of the page can then use. However, you can also just encapsulate your JavaScript functions or code snippets with the <script> tag and place them anywhere in the page, as needed. Listing 19.1 shows an example of a JavaScript snippet placed in the <body> of an HTML document.

Note

It is best practice to place scripts at the bottom of your page, just before the close of the <body> element. This ensures that your pages render without waiting to load the script. However, if you need the script to write content to the page, you need to write that content to the DOM rather than as plain HTML in the JavaScript, as otherwise it would just write that content at the end, which is likely not your intention.

Listing 19.1 Using JavaScript to Print Some Text

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Example</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>JavaScript Example</h1>
    <p>This text is HTML.</p>
    <script>
      <!-- Hide the script from old browsers
      document.write('<p>This text comes from JavaScript.</p>');
      // Stop hiding the script -->
    </script>
    <p>And this text is HTML again.</p>
  </body>
</html>

Between the <script></script> tags is a single JavaScript command that outputs the following HTML:

<p>This text comes from JavaScript.</p>

When the browser renders this HTML page, it sees the JavaScript between the <script></script> tags, stops for a millisecond to execute the command, and then returns to rendering the output that now includes the HTML output from the JavaScript command. It then continues to render the rest of the HTML in the document. Figure 19.1 shows that this page appears as any other HTML page appears. It’s an HTML page, but only a small part of the HTML comes from a JavaScript command.

A screenshot of the output rendered by an HTML file embedded with JavaScript. The output produced by the JavaScript is printed in the same way as the output rendered by the HTML script above and below it.
Figure 19.1 The output of a JavaScript snippet looks like any other output.

Note

You might have noticed these two lines in Listing 19.1:

<!-- Hide the script from old browsers
// Stop hiding the script -->

This is an HTML comment. Anything between the <!-- start and --> end will be visible in the source code but will not be rendered by the browser. In this case, JavaScript code is surrounded by HTML comments, on the off chance that your visitor is running a very old web browser or has JavaScript turned off. These days, nearly all browsers use or ignore JavaScript appropriately, but there’s no harm in commenting it out for very old browsers or screen readers that do not handle JavaScript at all. You will learn more about comments in Lesson 28, “Organizing and Managing a Website.”

Displaying Random Content

You can use JavaScript to display something different each time a page loads. Maybe you have a collection of text or images that you find interesting enough to include in your pages.

Lots of people are suckers for a good quote. You might find it fun to incorporate an ever-changing quote into your web pages. To create a page with a quote that changes each time the page loads, you must first gather all your quotes, along with their respective sources. You then place these quotes into a JavaScript array, which is a special type of storage unit in programming languages that is handy for holding lists of items.

After the quotes are loaded into an array, the JavaScript used to pluck out a quote at random is fairly simple (and explained momentarily). You’ve already seen the snippet that will print the output to your HTML page.

Listing 19.2 contains the complete HTML and JavaScript code for a web page that displays a random quote each time it loads.

Listing 19.2 A Random-Quote Web Page

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Quotable Quotes</title>
    <script>
      <!-- Hide the script from old browsers
      function getQuote() {
      // Create the arrays
      quotes = new Array(4);
      sources = new Array(4);
      
      // Initialize the arrays with quotes
      quotes[0] = "When I was a boy of 14, my father was so " +
      "ignorant...but when I got to be 21, I was astonished " +
      "at how much he had learned in 7 years.";
      sources[0] = "Mark Twain";
      
      quotes[1] = "Everybody is ignorant. Only on different " +
      "subjects.";
      sources[1] = "Will Rogers";
      
      quotes[2] = "They say such nice things about people at " +
      "their funerals that it makes me sad that I'm going to " +
      "miss mine by just a few days.";
      sources[2] = "Garrison Keillor";
      
      quotes[3] = "What's another word for thesaurus?";
      sources[3] = "Steven Wright";
      
      // Get a random index into the arrays
      i = Math.floor(Math.random() * quotes.length);
      
      // Write out the quote as HTML
      document.write("<p style='background-color: #ffb6c1' >"");
      document.write(quotes[i] + """);
      document.write("<em>- " + sources[i] + "</em>");
      document.write("</p>");
      }
      // Stop hiding the script -->
    </script>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Quotable Quotes</h1>
    <p>Following is a random quotable quote. To see a new quote
    just reload this page.</p>
    
    <script>
      <!-- Hide the script from old browsers
      getQuote();
      // Stop hiding the script -->
    </script>
  </body>
</html>

Although this code looks kind of long, a lot of it consists of just the four quotes available for display on the page.

The large number of lines between the first set of <script></script> tags is creating a function called getQuote(). After a function is defined, it can be called in other places in the same page, as you see later in the code. Note that if the function existed in an external file, the function could be called from all your pages.

If you look closely at the code, you will see some lines like this:

// Create the arrays

and this:

// Initialize the arrays with quotes

These are code comments. A developer uses these types of comments to leave notes in the code so that anyone reading it has an idea of what the code is doing in that particular place. After the first comment about creating the arrays, you can see that two arrays are created—one called quotes and one called sources, each containing four elements:

quotes = new Array(4);
sources = new Array(4);

After the second comment (about initializing the arrays with quotes), four items are added to the arrays. Let’s look closely at one of them, the first quote by Mark Twain:

quotes[0] = "When I was a boy of 14, my father was so " +
"ignorant...but when I got to be 21, I was astonished at " +
"how much he had learned in 7 years.";
sources[0] = "Mark Twain";

You already know that the arrays are named quotes and sources. But the variables to which values are assigned (in this instance) are called quotes[0] and sources[0]. Because quotes and sources are arrays, each item in the array has its own position. When you’re using arrays, the first item in the array is not in slot 1; it is in slot 0. In other words, you begin counting at 0 instead of 1, which is typical in programming. (Just file this away as an interesting and useful note for the future…or a good trivia answer.) Therefore, the text of the first quote (a value) is assigned to quotes[0] (a variable). Similarly, the text of the first source is assigned to source[0].

Text strings are enclosed in quotation marks. However, in JavaScript, a line break indicates the end of a command, so the following would cause problems in the code:

quotes[0] = "When I was a boy of 14, my father was so
ignorant...but when I got to be 21, I was astonished at
how much he had learned in 7 years.";

Therefore, you see that the string is built as a series of strings enclosed in quotation marks, with a plus sign (+) connecting the strings. (This plus sign is called a concatenation operator.)

The next chunk of code definitely looks the most like programming. This line is generating a random number and assigning that value to a variable called i:

i = Math.floor(Math.random() * quotes.length);

But you can’t just pick any random number; the purpose of the random number is to determine which of the quotes and sources should be printed, and there are only four quotes. So, this line of JavaScript does the following:

  • Image Uses Math.random() to get a random number between 0 and 1. For example, 0.5482749 might be a result of Math.random().

  • Image Multiplies the random number by the length of the quotes array, which is currently 4; the length of the array is the number of elements in the array. If the random number is 0.5482749 (as shown previously), multiplying that by 4 results in 2.1930996.

  • Image Uses Math.floor() to round the result down to the nearest whole number. In other words, 2.1930996 turns into 2.

  • Image Assigns the variable i a value of 2 (for example).

The rest of the function should look familiar, with a few exceptions. First, as you learned earlier this lesson, document.write() is used to write HTML that the browser then renders. Next, the strings are separated to clearly indicate when something needs to be handled differently, such as escaping the quotation marks with a backslash when they should be printed literally () or when the value of a variable is substituted. The actual quote and source that are printed are the ones that match quotes[i] and sources[i], where i is the number determined by the mathematical functions noted previously.

But the act of simply writing the function doesn’t mean that any output will be created. Further on in the HTML, you can see getQuote(); between two <script></script> tags; this is how the function is called. Wherever that function call is made is where the output of the function will be placed. In this example, the output displays below a paragraph that introduces the quotation. This is not the best way to write JavaScript, as it is obtrusive and places behavior and interactivity within the HTML document itself. Later in this lesson, you will learn how to write unobtrusive JavaScript and how to write this script unobtrusively.

Figure 19.2 shows the Quotable Quotes page as it appears when loaded in a web browser. When the page reloads, there is a one in four chance that a different quote will display—it is random, after all!

A screenshot of the Quotable quotes web page that reads a random quote at the bottom. The quote area is highlighted with a background color.
Figure 19.2 The Quotable Quotes page displays a random quote each time it is loaded.

Keep in mind that you can easily modify this page to include your own quotes or other text that you want to display randomly. You can also increase the number of quotes available for display by adding more entries in the quotes and sources arrays in the code. And, of course, you can modify the HTML output and style it however you’d like.

If you use the Quotable Quotes page as a starting point, you can easily alter the script and create your own interesting variation on the idea. And if you make mistakes along the way, so be it. The trick to getting past mistakes in script code is to be patient and carefully analyze the code you’ve entered. You can always remove code to simplify a script until you get it working and then add new code one piece at a time to make sure each piece works.

Understanding the Document Object Model

As you’ve read, client-side interactivity using JavaScript typically takes the form of manipulating the Document Object Model in some way. The DOM is the invisible structure of all documents; it is not the HTML structure or the way in which you apply semantic formatting but a sort of overall framework or container. If this description seems vague, that’s because it is; the DOM is not a tangible object.

The overall container object is called the document. Any container that you create within the document to which you’ve given an ID can be referenced by that ID. For example, if you have a <div> with the ID wrapper, then in the DOM that element is referenced as follows:

document.wrapper

For example, you can change the visibility of a specific element by changing the style object associated with it. Similarly, if you wanted to access the background-color style of the <div> with an ID called wrapper (to then do something with it), it would be referred to as follows:

document.wrapper.style.background-color

To change the value of this style to something else, perhaps based on an interactive user event, use the following to change the color to white:

document.wrapper.style.background-color="#ffffff"

The DOM is the framework to refer to elements and their associated objects. Obviously, this is a brief overview of something quite complicated, but at least you can now begin to grasp what this document-dot-something business is all about. To learn a lot more about the DOM, visit the World Wide Web Consortium’s information about the DOM at www.w3.org/DOM/.

What Is Unobtrusive JavaScript?

Unobtrusive JavaScript is an approach to writing JavaScript scripts. You don’t need to use it to create interactive web pages, but best practices recommend that you at least consider it. There are four general rules to unobtrusive JavaScript, developed by the Web Standards Project:

  • Image It should be usable—JavaScript should work without being noticed by the user. Customers should be able to use it without thinking about it.

  • Image It should be easily degradable—When an unobtrusive script fails, it should not generate an error message. Instead, it should present the features or silently disappear.

  • Image Make it accessible—The page should not rely on JavaScript for core functions.

  • Image Keep it separate from structure and style—JavaScript should be maintained as separate files from the HTML and CSS.

Many of these rules are reminiscent of the Mobile First approach to web design. By using unobtrusive JavaScript, you will ensure that your pages work more effectively on mobile and nonmobile devices.

Using the DOM to Make a Script Unobtrusive

The script in Listing 19.2 is written in the standard style of JavaScript. Several factors prevent this script from being unobtrusive. The most prominent is that the script is not separate from the HTML. The line that reads getQuote(); must be placed right within the HTML where the quote will be displayed. This means the core functionality of the page—displaying a quotation—is stored only in the JavaScript. If the script fails or if the browser can’t load the script, the quote won’t be displayed. It also means that the JavaScript is not separated from the HTML.

To make the Quotable Quotes page unobtrusive, you need to make a few changes. The first change is to add an HTML element in the document where the quote will be placed:

<blockquote id="quote">All cats are black after midnight.</blockquote>

It doesn’t have to be a <blockquote>, but as it is a quotation, this seems like the most appropriate HTML element. Notice that there is text inside the <blockquote> element: “All cats are black after midnight.” This makes the script unobtrusive because if it can’t run for some reason, the customer still gets a quotation.

Because the <blockquote> element has an ID (quote), it can be referenced in the JavaScript:

blockquote = document.getElementById("quote");

Then you simply update the contents of that tag with the JavaScript innerHTML property:

blockquote.innerHTML = quotes[i];

The last thing you need to do is either move the script to an external JavaScript file or place it as the last HTML element on the page before the closing </body> tag. Doing so removes the script from the HTML. Listing 19.3 shows how the entire page looks, including an additional paragraph for the source of each quote that is to be displayed as well.

Listing 19.3 The Quotable Quotes Page, Made Unobtrusive

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Quotable Quotes - Unobtrusively</title>
    <meta name="viewport"
          content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Quotable Quotes - Unobtrusively</h1>
    <p>Following is a random quotable quote. To see a new quote
    just reload this page.</p>
    <blockquote id="quote">All cats are black after
      midnight.</blockquote>
    <p id="source">Robert A. Heinlein</p>
    
    <script>
      <!-- Hide the script from old browsers
      function getQuote() {
        // Create the arrays
        quotes = new Array(4);
        sources = new Array(4);
        
        // get the elements to write to by their ID
        blockquote = document.getElementById("quote");
        source = document.getElementById("source");
        
        // Initialize the arrays with quotes
        quotes[0] = "When I was a boy of 14, my father was so " +
        "ignorant...but when I got to be 21, I was astonished " +
        "at how much he had learned in 7 years.";
        sources[0] = "Mark Twain";
        
        quotes[1] = "Everybody is ignorant. Only on different " +
        "subjects.";
        sources[1] = "Will Rogers";
        
        quotes[2] = "They say such nice things about people at " +
        "their funerals that it makes me sad that I'm going to " +
        "miss mine by just a few days.";
        sources[2] = "Garrison Keillor";
        
        quotes[3] = "What's another word for thesaurus?";
        sources[3] = "Steven Wright";
        
        // Get a random index into the arrays
        i = Math.floor(Math.random() * quotes.length);
        
        // Write the quote to the DOM
        blockquote.innerHTML = quotes[i];
        source.innerHTML = sources[i];
      }

      getQuote();
      // Stop hiding the script -->
    </script>
  </body>
</html>

The unobtrusive version of this script also removes the styles from the quotation, but you can add them by using style sheets, just as you would for any other web page.

Changing Images Based on User Interaction

Lesson 4 introduced you to the concept of user interaction events, such as onclick. In that lesson, you invoked changes in window display based on user interaction; in this section, you’ll see an example of a visible type of interaction that is both practical and dynamic.

Figure 19.3 shows a page that contains one large image with some text next to it and three small images farther down the page. If you look closely at the list of small images, you might notice that the first small image is, in fact, a smaller version of the large image that is displayed. This is a common display for a type of small gallery, such as one that you might see in an online catalog, in which an item has a description and a few alternate views of the product. Although close-up images of the details of products are important to a potential buyer, using several large images on a page becomes unwieldy from both display and bandwidth points of view, so using this type of gallery view is a popular way to display alternative images. We don’t personally have products to sell, but we do have pictures of big trees that we can use as an example, as shown in Figure 19.3.

A screenshot shows an example of clicking thumbnails and viewing them in a webpage.
Figure 19.3 An informational page with a main image and alternative images ready to click and view.

The large image on the page is called using this <img> tag:

<img
   id="large_photo"
   style="border: 1px solid black; margin-right: 13px;"
   src="mariposa_large_1.jpg"
   alt="large photo">

The style, src, and alt attributes should all make sense to you at this stage of the game. In addition, as you can see, this image is given the ID large_photo. Therefore, this image exists in the DOM as document.images['large_photo'] (an image is referred to by its ID). This is important because a bit of JavaScript functionality enables you to dynamically change the value of document.images['large_image'].src, which is the source (src) of the image.

The following code snippet creates the third small image in the group of three images shown at the bottom of Figure 19.3. The onclick event indicates that when the user clicks on this small image, the value of document.images['large_image'].src—the large image slot—is filled with the path to a matching large image:

<a href="#"
  onclick="javascript:document.images['large_photo'].src =
'mariposa_large_1.jpg'">
<img
  style="border: 1px solid black; margin-right: 3px;"
  src="mariposa_small_1.jpg"
  alt="photo #1"></a>

Figure 19.4 shows the same page but not reloaded by the user. The slot for the large image is filled by a different image when the user clicks on one of the other smaller images at the bottom of the page.

 A screenshot shows the result of clicking a thumbnail in the Swapping Images webpage. The second thumbnail is selected and the image in the image area shows is changed to the selected one.
Figure 19.4 The large image is replaced when the user clicks on a smaller one.

If you’ve been paying attention, you will realize that this script is not unobtrusive. In fact, the easiest way to determine if a script is unobtrusive is to see if there is JavaScript inside any HTML attributes. In this case, the onclick attribute is holding the JavaScript that makes the page work, and this makes it obtrusive JavaScript.

To make this script unobtrusive, you need to move the JavaScript out of the links and into a separate script file. There are many ways you could do this, but they are beyond the scope of this lesson. One good place to learn more about unobtrusive JavaScript is in the book Sams Teach Yourself JavaScript in 24 Hours.

Thinking Ahead to Developing HTML5 Applications

We’re not going to lie: There’s a pretty big difference between a basic website built with HTML, CSS, and a little JavaScript and a comprehensive application that uses some of the advanced features of HTML5 and the latest JavaScript frameworks. But it’s important to your understanding of HTML, the language of the Web, to have some idea of just how far you can extend it—and it’s pretty far, as it turns out. Beyond basic markup, HTML5 extends to include APIs (application programming interfaces) for complex applications, beginning with the native integration of audio and video elements, as you learned in previous lessons, and going all the way to built-in offline storage mechanisms that allow full-blown applications to be accessed and run (and data stored on the client side) even without a network connection.

Although HTML5 is incredibly rich, the creation of highly interactive HTML5 websites and applications—including mobile applications—doesn’t happen in isolation. Interactivity comes when HTML5 is paired with a client-side language such as JavaScript, which then reaches back into the server and talks to a server-side language (PHP, Ruby, Python, and so on) through a persistent connection called a web socket. With this connection open and talking to some server-side code that is (for example) talking to a database or performing some calculation, the browser can relay a bundle of information that is additionally processed by JavaScript and finally rendered in HTML5. Be it a video game, a word processing program, or an email or Twitter client, just to name a few popular types of HTML5 applications, the combination of the advanced features of HTML5 plus JavaScript—and, specifically, the feature-rich JavaScript libraries such as Angular (https://angular.io), jQuery (http://jquery.com), and React (https://reactjs.org)—really makes the opportunities limitless when it comes to application creation. We will go into more detail about these libraries in Lesson 26, “Using Third-Party JavaScript Libraries and Frameworks.”

The depth of the technologies involved in HTML5 application creation is beyond the scope of these lessons, but the foundation you should have in standards-compliant HTML5, CSS3, and JavaScript will serve you well if you begin to think outside the box of a basic website. To learn more about HTML5 application creation, take a look at my book Sams Teach Yourself HTML5 Mobile Application Development in 24 Hours for an introduction to some of the core features. Throughout these lessons, you get a solid foundation in the basics of HTML5. We are confident that, with additional instruction, you can take the next step and begin to learn and build basic interactions in an HTML5 application.

Summary

In this lesson, you learned about the differences between server-side scripting and client-side scripting, and you learned how to include JavaScript in your HTML files to add a little interactivity to your websites. You also learned how to use the JavaScript document.write() method to display random quotes upon page load. Finally, you learned a bit about the Document Object Model and how to write unobtrusive scripts.

By applying the knowledge you’ve gained from the preceding lesson, you’ve learned how to use client-side scripting to make images on a web page respond to mouse movements. Although they are simple in their construction, these types of interactions are some of the basic JavaScript-based interactions that form the foundation of web applications. Hopefully this will spur your desire to learn more about server-side programming so that you can give your websites even more complex interactive features, including taking a step into the world of creating HTML5 applications.

Q&A

Q. If I want to use the random-quote script from this lesson, but I want to have a library of a lot of quotes, do I have to put all the quotes in each page?

A. Yes. Each item in the array must be there. This is where you can begin to see a bit of a tipping point between something that can be client side and something that is better dealt with on the server side. If you have a true library of random quotations and only one is presented at any given time, it’s probably best to store those items in a database table and use a little piece of server-side scripting to connect to that database, retrieve the text, and print it on the page. Alternatively, you can always continue to carry all the quotes with you in JavaScript, but you should at least put that JavaScript function into a different file that can be maintained separately from the text. Just be aware that the more quotes you have in the JavaScript, the longer your page will take to fully load.

Q. I’ve seen some online catalogs that display a large image in what looks to be a layer on top of the website content. I can see the regular website content underneath it, but the focus is on the large image. How is that done?

A. This sounds like an effect created by a JavaScript library called Lightbox. The Lightbox library enables you to display an image or a gallery of images in a layer that is placed over your site content. This is a very popular library for showing the details of large images or just a set of images deemed important enough to showcase “above” the content. The library is freely available from its creator, Lokesh Dhakar, at http://lokeshdhakar.com/projects/lightbox/. To install and use it, follow the instructions included with the software; you will be able to integrate it into your site using the knowledge you’ve gained in the lessons so far.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. You’ve made a button image and named it button.gif. You’ve also made a simple GIF animation of the button so that it flashes green and white. You’ve named that GIF flashing.gif. What HTML and JavaScript code can you use to make the button flash whenever a user moves the mouse pointer over it and also link to a page named gohere.html when a user clicks the button?

  1. <a href="gohere.html"
    onclick="javascript:document.images['flasher'].src='flashing.gif'"
    onhover="javascript:document.images['flasher'].src='button.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  2. <a href="gohere.html"
    onmouse="javascript:document.images['flasher'].src='flashing.gif'"
    onmouse="javascript:document.images['flasher'].src='button.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  3. <a href="gohere.html"
    onmouseover="javascript:document.images['flasher'].src='flashing.gif'"
    onmouseout="javascript:document.images['flasher'].src='button.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  4. <a href="gohere.html"
    onover="javascript:document.images['flasher'].src='flashing.gif'"
    onout="javascript:document.images['flasher'].src='button.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

2. How can you modify the code you wrote for Question 1 so that the button flashes when a user moves the mouse over it and continues flashing even if the user then moves the mouse away from it?

  1. <a href="gohere.html"
    onmouse="javascript:document.images['flasher'].src='flashing.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  2. <a href="gohere.html"
    onmouseover="javascript:document.images['flasher'].src='flashing.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  3. <a href="gohere.html"
    onmouseout="javascript:document.images['flasher'].src='button.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

  4. <a href="gohere.html"
    onover="javascript:document.images['flasher'].src='flashing.gif'">
    <img src="button.gif" id="flasher" style="border-style:none;"></a>

3. Is the JavaScript in Questions 1 and 2 unobtrusive? Why or why not?

  1. Yes, it is unobtrusive because it works without any errors.

  2. Yes, it is unobtrusive because it uses valid HTML.

  3. No, it is not unobtrusive because it uses the onmouseover attribute to place the JavaScript right in the HTML.

  4. No, it is not unobtrusive because it creates a flashing image.

4. What are two examples of server-side scripting languages?

  1. JavaScript and Python

  2. Perl and ActiveX

  3. Perl and Ruby

  4. JavaScript and ActiveX

5. How is JavaScript related to Java?

  1. JavaScript is a sub-set of Java.

  2. JavaScript uses Java methods.

  3. JavaScript is a scripting language for Java.

  4. JavaScript is not related to Java.

6. Where can you store JavaScript?

  1. In the HTML

  2. In a separate file

  3. On a local hard drive

  4. Both A and B

7. If you use a <script> tag to store your JavaScript, where is it best to place it in order to create unobtrusive JavaScript?

  1. Right after the <html> tag

  2. Right before the </head> tag

  3. Right after the </head> tag

  4. Right before the </body> tag

8. What is the JavaScript to generate a random number?

  1. Math.random()

  2. Math.randomNum()

  3. MathRandom()

  4. Rand()

9. What does the Math.floor() function do?

  1. Rounds the result down to the nearest whole number

  2. Rounds the result down to the smallest number possible

  3. Rounds the result up to the largest number possible

  4. Rounds the result up to the nearest whole number

10. What does the plus sign mean in the following context?

document.write('This is a text string ' + 'that I have created.');

  1. The plus sign (+) adds two numbers together.

  2. The plus sign (+) adds the value of two strings together to generate a number.

  3. The plus sign (+) joins a string and a number.

  4. The plus sign (+) joins two strings together.

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. c. Your code might look something like this:

<a href="gohere.html"
onmouseover="javascript:document.images['flasher'].src='flashing.gif'"
onmouseout="javascript:document.images['flasher'].src='button.gif'">
<img src="button.gif" id="flasher" style="border-style:none;"></a>

2. b. Your code might look something like this:

<a href="gohere.html"
onmouseover="javascript:document.images['flasher'].src='flashing.gif'">
<img src="button.gif" id="flasher" style="border-style:none;"></a>

3. c. No, it is not unobtrusive because it uses the onmouseover attribute to place the JavaScript right in the HTML.

4. c. Some server-side scripting languages include Python, Ruby, PHP, and Perl.

5. d. JavaScript is not related to Java. It has a similar name, but that is the only relationship.

6. d. JavaScript can be stored in a separate file with a .js extension or directly in the HTML in the <script> tag.

7. d. To create unobtrusive JavaScript, you should place all <script> tags as close to the bottom of your document as possible. If you cannot place them directly before the </body> tag, then placing them last in the <head></head> element is acceptable as well.

8. a. Math.random() is the JavaScript function used to generate a random number.

9. a. The Math.floor() function rounds the result down to the nearest whole number.

10. d. The plus sign (+) joins two strings together.

Exercises

  • Image Do you have any pages that would look flashier or be easier to understand if the navigation icons or other images changed when the mouse passed over them? If so, try creating some highlighted versions of the images and try modifying your own page by using the information presented in this lesson.

  • Image You can display random images—such as graphical banners or advertisements—in the same way you learned to display random content using JavaScript earlier in this lesson. Instead of printing text, just print the <img> tag for the images you want to display.

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

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