Hour 21. Understanding Dynamic Websites and HTML5 Applications


What You’ll Learn in This Hour:

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 using JavaScript and user events

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


The term dynamic means something active or something that motivates another person to become active. When talking about websites, a dynamic website is one that incorporates interactivity into its functionality and design, but also motivates a user to take an action—read more, purchase a product, and so on. In this hour, you learn about the different 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).

I’ve mentioned client-side scripting elsewhere in this book, and you used a little of it in Hour 18, “Using Mouse Actions to Modify Text Display,” when you used event attributes and JavaScript to change the styles of particular elements—that is called manipulating the Document Object Model (DOM). You do a bit more of that type of manipulation in this hour. Specifically, after learning about the different technologies, you use JavaScript to display a random quote upon page-load and swap images based on user interaction. Finally, having learned at least the keywords and the basic concept of putting together the HTML, CSS, and JavaScript pieces together, you’re introduced to the possibilities that exist when creating HTML5 applications.

Understanding the Different Types of Scripting

In web development, two different 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 this book. However, they are not too far beyond this book. Two very useful and popular books in the Sams Teach Yourself series are natural extensions of this one: Sams Teach Yourself PHP, MySQL and Apache 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):

Image PHP (PHP: Hypertext Preprocessor)http://www.php.net/

Image Rubyhttp://www.ruby-lang.org/

Image Pythonhttp://www.python.org/

Image Perlhttp://www.perl.org/

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. For several years, research has shown that more than 98 percent of all web browsers have JavaScript enabled.


Tip

Despite its name, JavaScript is not a derivation of or any other close relative to 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.


Another client-side scripting language is Microsoft’s VBScript (Visual Basic Scripting Edition). This language is available only with the Microsoft Internet Explorer web browser and, therefore, should not be used unless you are very sure that users will access your site with that web browser (such as in a closed corporate environment). Given a desire to reach the largest possible audience, this hour assumes the use of JavaScript for client-side scripting; the coding examples in this lesson are all JavaScript.

Including JavaScript in HTML

JavaScript code can live in one of two places within 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), while 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 type="text/javascript" src="/path/to/script.js"></script>


Note

It is also quite common to find scripts loaded 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, you cannot use this method of loading scripts if you also use your scripts to write content out to the page—it would just write it at the end, which is likely not your intention.


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 21.1 shows an example of a JavaScript snippet placed in the <body> of an HTML document.

LISTING 21.1 Using JavaScript to Print Some Text


<!DOCTYPE html>

<html lang="en">
  <head>
    <title>JavaScript Example</title>
  </head>

  <body>
    <h1>JavaScript Example</h1>
    <p>This text is HTML.</p>
    <script type="text/javascript">
    <!-- Hide the script from old browsers
    document.write('<p>This text comes from JavaScript.</p>'),
    // Stop hiding the script -->
    </script>
  </body>
</html>


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

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


Tip

You might have noticed these two lines in Listing 21.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 screenreaders that do not handle JavaScript at all.


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. Figure 21.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.

Image

FIGURE 21.1 The output of a JavaScript snippet looks like any other output.

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.

I’m a sucker for a good quote. If you’re like me, or plenty of other people creating personal websites, 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 (we explain it momentarily). You’ve already seen the snippet that will print the output to your HTML page.

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

LISTING 21.2 A Random Quote Web Page


<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Quotable Quotes</title>

    <script type="text/javascript">
      <!-- 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>
  </head>

  <body>
    <h1>Quotable Quotes</h1>
    <p>Following is a random quotable quote. To see a new quote just
    reload this page.</p>
    <script type="text/javascript">
      <!-- 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, which 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

// 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, the items in the array each have their own position. When 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 that 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 an 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:

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

• 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.

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

• 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 hour, 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 is printed is the one that matches 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—that is how the function is called. Wherever that function call is made, that is where the output of the function will be placed. In this example, the output displays below a paragraph that introduces the quotation.

Figure 21.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 displays—it is random, after all!

Image

FIGURE 21.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

This section could also be called “The Least You Need to Know About the Document Object Model to Begin Working with It and Learning More in the Future,” but that would make for a terrible section title even if it is true. As you’ve read, client-side interactivity using JavaScript typically takes the form of manipulating the Document Object Model (DOM) in some way. The DOM is the invisible structure of all documents—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; it’s not a tangible object.

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

document.wrapper

Recall that, in Hour 18, you changed the visibility of a specific element by changing something in 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 that 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 behind your ability to refer to elements and their associated objects in this way. 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 information about the DOM at http://www.w3.org/DOM/.

Changing Images Based on User Interaction

Hour 18 introduced you to the different types of user interaction events, such as onclick, onmouseover, and onmouseout. In that hour, you invoked changes in text based on user interaction; in this section, you see an example of a visible type of interaction that is both practical and dynamic.

Figure 21.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 the potential buyer, using several large images on a page becomes unwieldy from both a display and bandwidth point of view, so this type of gallery view is a popular way to display alternative images. I don’t personally have products to sell, but I do have pictures of big trees that I can use as an example (see Figure 21.3).

Image

FIGURE 21.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. Additionally, as you can see, this image is given an ID of large_photo. Therefore, this image exists in the DOM as document.images['large_photo']—images are referred to by their ID. This is important because a bit of JavaScript functionality enables us 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 21.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 21.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 the third of the smaller images at the bottom of the page.

Image

FIGURE 21.4 The large image is replaced when the user clicks on a smaller one.

Thinking Ahead to Developing HTML5 Applications

I’m not going to lie—there’s a pretty big difference between a basic website built with HTML and CSS, and advanced applications that use some of the advanced features of HTML5. 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 (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 (such as 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 jQuery (jquery.com)—really makes the opportunities limitless when it comes to application creation.

The depth of the technologies involved in HTML5 application creation is beyond the scope of this basic book, but the foundation you should have in standards-compliant HTML5 and CSS3 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 Sams Teach Yourself HTML5 Mobile Application Development in 24 Hours for an introduction to some of the core features. Throughout this book, you get a solid foundation in the basics of HTML5. I am 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 hour, 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.

By applying the knowledge you’ve gained from previous hours, you’ve learned how to use client-side scripting to make images on a web page respond to mouse movements. None of these tasks requires much in the way of programming skills, but they might inspire you to learn more about JavaScript or a server-side programming language so that you can give your pages 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. Alternately, 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.

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. The description 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 used to show 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 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 this book 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 picture of a button 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?

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?

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

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

Answers

1. 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. 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. 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 using the information presented in this hour.

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 chapter. 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
3.144.18.198