Hour 21. Understanding Dynamic Web Sites

The term dynamic means something active or something that motivates another to become active.

When talking about web sites, a dynamic web site 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’ll learn a little bit 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 when you used event attributes and JavaScript to change the styles of particular elements—that is called manipulating the Document Object Model (DOM). You will do a bit more of that type of manipulation in this chapter. Specifically, after learning about the different technologies, you’ll use JavaScript to display a random quote upon page-load and swap images based on user interaction.

Understanding the Different Types of Scripting

In web development, there are two different types of scripting: server-side and client-side. Both types of scripting—which is, in fact, 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 web site, which includes using a search engine, you have experienced the results of a server-side script. Popular server-side scripting languages include the following; to learn more, visit the web sites listed here:

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

• JSP (Java Server Pages)—http://java.sun.com/products/jsp/

• ASP (Active Server Pages)—http://www.asp.net/

• Perl—http://www.perl.org/

• Python—http://www.python.org/

• Ruby—http://www.ruby-lang.org/

On the other hand, client-side scripting refers to scripts that run within your web browser—there is no interaction with a web server in order for the scripts to run. The most popular client-side scripting language, by far, is JavaScript. For several years, research has shown that more than 93 percent of all web browsers have JavaScript enabled.

Note

Despite its name, JavaScript is not a derivation or any other close relative to the object-oriented programming language called Java. Released by Sun Microsystems in 1995, Java is very 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 only available with 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:

• In its own file with a .js extension.

• Directly in your HTML files.

External files are often used for script libraries (code you can reuse throughout many pages), while code appearing 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:

image

These <script></script> tags are typically placed between the <head></head> tag because it is not, strictly speaking, 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

image

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

image

When the browser renders this HTML page, it sees the JavaScript between the <script></script> tags, stops for a millisecond to execute the command, 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.

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

image

Note

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

Displaying Random Content

You can use JavaScript to display something different each time a page is loaded. 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, 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 together, along with their respective sources. You’ll 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. You’ve already seen the snippet that will print the output into 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

image

image

Although this code looks kind of long, if you look carefully, you’ll see that a lot of it consists of the four quotes available for display on the page. After you get past the length, the code itself isn’t too terribly complex.

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

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

image

and

image

These are code comments. The developer uses these 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:

image

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

image

You already know that the arrays are named quotes and sources. But the variable 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 will 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. 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, such that the following would cause problems in the code:

image

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

The next chunk of code definitely looks the most like programming; this line gets a random number:

image

But you can’t just pick any random number, because 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:

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

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 which is then rendered by the browser. Next, the strings are separated in such a way as to make it clear 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 above.

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 a different quote displays—it is random, after all!

Figure 21.2 The Quotable Quotes page displays a random quote each time it is loaded.

image

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.

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

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 levels of 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 within the document that has an ID is referenced by that ID. For example, if you have a <div> with an ID called wrapper, then in the DOM that element is referenced by:

image

In Hour 17, you changed the visibility of a specific element by changing something in the style object associated with it. If you wanted to access the background-color style of the <div> with an ID called wrapper, it would be referred to as:

image

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:

image

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’s information about the DOM at http://www.w3.org/DOM/.

Changing Images Based on User Interaction

In Hour 18 you were introduced to the different types of user interaction events, such as onclick, onmouseover, onmouseout, and so on. In that hour, you invoked changes in text 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 21.3 shows a page from an online catalog for a collectibles company. Each page in the catalog shows a large image, information about the item, and a set of smaller images at the bottom of the page. In this type of catalog, close-up images of the details of each item are important to the potential buyer, but several large images on a page becomes unwieldy from both a display and bandwidth point of view.

Figure 21.3 The catalog item page when first loaded by the user.

image

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

image

As you can see, this image is given a name of product_img. Therefore, this image exists in the DOM as document.product_img. This is important because a little bit of JavaScript functionality allows us to dynamically change the value of document.product_img.src, which is the source (src) of the image.

The following code snippet creates the fourth small image in the group of five images shown at the bottom of Figure 21.3. The onmouseover event indicates that when the user rolls over this small image, the value of document.product_img.src—the large image slot—is filled with the path to a matching large image.

image

Figure 21.4 shows the same page—not reloaded by the user—whereby the slot for the large image is filled by a different image when the user rolls over a smaller image at the bottom of the page. The mouse pointer hovers over the second image from the right. As the user rolls over the small version of the interior photo, the large version of it is shown in the top area on the page.

Figure 21.4 The large image is replaced when the user rolls over a smaller one.

image

Summary

In this hour, you’ve learned about the differences between server-side scripting and client-side scripting and you’ve learned how to include JavaScript in your HTML files in order to add a little interactivity to your web sites. You also learned how to use the JavaScript document.write() method to display random quotes upon page load. Lastly, you learned what the Document Object Model is all about.

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 you can give your pages more complex interactive features.

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 has to 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 web site content — I can see the regular web site 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 allows 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, as it were. The library is freely available from its creator at http://www.huddletogether.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

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 whereby it flashes green and white. You’ve named that GIF flashing.gif. What HTML and JavaScript code would 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 would you modify the code you wrote for Question 1 so that the button flashes when a user moves his mouse over it and continues flashing even if he moves the mouse away from it?

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

image

Answers

1. Your code might look something like this:

image

2. Your code might look something like this:

image

3. The plus sign (+) is used to join two strings together.

Exercises

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

• 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