Hour 15
Having Fun with JavaScript

Now is the time to sit back and have some fun with JavaScript. Sure, programming is fun in itself, and you already know how easy and enjoyable writing programs can be. Nevertheless, unlike with Python, with JavaScript you can easily do more than write data-processing programs for business and engineering. You can also use JavaScript to jazz up your websites.

The material presented in this hour gives you a framework for adding pizzazz to your programs. You will get an idea of how game programmers do their jobs. You will learn some fundamental concepts that you need in order to write programs that capture a user’s attention.

The highlights of this hour include the following:

Image Rotating images on a page

Image Adding interactivity to your web photos

Image Using the onmouseover() event

Image Adding a ticker to your website

Rotating Images on a Page

Static pages can be boring pages. If your business is trying to attract customers or if you’re showing off your favorite photos of your children, your garden, or your dog, a single photo is nice, but a series of photos can be even better. You can use your knowledge of arrays and other programming constructs to create a photo rotation for a page.

By setting up an array of images in the header, you can easily go back and add more pictures or delete some pictures as needed. When you declare an array, you first let JavaScript know an element is an image with the Image() function, and then you can set the .src for each element in the array to a .jpg image. If your .jpg photos are in the same directory as the .html file, you don’t need to type in the entire file directory path. You can also use a web address there for your filenames. Adding an additional photo is as simple as adding two additional lines: a subsequent new image() call, and then a file location setting.

When your array is set, it’s time to create a function to rotate the images in the array. Despite being less than 10 lines of code, the rotator function probably looks a bit intimidating. It shouldn’t. The method document.getElementbyId is used to set image1 to the first element in your array of photos, famPhotos[0]. It gets this element because before you defined the function, you set i to 0. However, after it sets image1 to famPhotos[0], it increments the variable i by 1. This means the next time the function is called, it will set image1 to the second element in your array of photos, famPhotos[1]. This method keeps setting the image to a new element in your array of photos until it reaches the last element. That’s when the handy if statement jumps in. If i is incremented to 1 past the last element of the array, the if statement automatically resets i to 0, and you can loop through the images in the photo array again from the beginning.

In the last line of code, setTimeout() is a handy JavaScript function that keeps calling your rotator function (and therefore places new photos on the page) but waits a set amount of time. The last number, currently set to 2,000, is the delay and is equal to milliseconds. So 2,000 is a 2-second delay. Feel free to experiment with this number to create different transition delays. Be careful not to use a number that is too small; I got a bit of a headache watching my photos rotate every 200 milliseconds.

That’s it for the function. All that’s left is to call the function in the body of the HTML document. The function is called within the body definition by way of the onload event. This ensures that the code function runs as soon as everything is loaded on the page. Within the body, you use a little HTML to set a heading for the page and a little text before image1 is placed. (HTML is covered in greater detail in Hour 13, “HTML5 and CSS3.”) The information that follows image1 on that line sets the width and height of the image as well as the size and color of the image’s border. You can also experiment with these numbers (and colors) to get different effects.

Note

By default, all images have the same aspect ratio, so if you mix portrait and landscape pictures, some photos will be stretched to fit the box. Your photos will look best if you choose a set of photos that are either all portrait or all landscape.

Adding Interactivity to Your Web Photos

Another way to add value to your web page is to make your graphics and photos interactive. The best web pages are not static but give the user a chance to interact. Thinking back to our small store example from earlier hours, it would be nice to create a page with photos of products in inventory. Obviously, you could also add product information—such as a description and price—next to or under the photos, but you could make the page cleaner by showing only photos and having information pop up when a user clicks on a photo. JavaScript can make this type of interactivity possible, thanks to the onclick() method. Within each photo placement line, you can add the onclick() method, which runs a chunk of JavaScript code when the user clicks a specific photo.

Tip

Each of the three photos placed on the page in Figure 15.2 has a border of a different color (red, blue, and black). Normally, using consistently colored borders would make for a more elegant web design, but this example shows you the variety of color you can add to a page.

The code presented here is also as simple as can be—a single line of information presented to the screen in an alert() method. Sometimes a simple line of information is all you need. However, if you want to present more information or build a more complex function that executes upon a mouse click, you can do that as well.

Capturing the Position of the Mouse

Giving your website visitors additional information when they click a photo or some other object on your page is a nice way to add complexity to your website. However, you can give additional data without even requiring a click from the user. As discussed in Hour 14, “JavaScript,” JavaScript has a built-in method that captures the position of the mouse and can trigger some code if the user moves the mouse pointer over a specific photo or other object.

Tip

If you want the text to disappear when the mouse pointer leaves the image or object, there is a second method, onmouseout(), that you can use to trigger different code when the mouse is no longer in the specific area. Often these two methods are used in concert to achieve a specific “on and off” effect.

The alert box in this example can be a little clunky because visitors cannot do more on the page until the box is dismissed. As an additional project, you could try to alter the code in the functions to place text on the page instead of in an alert box.

Adding a Repeating News Ticker to Your Website

Another cool feature you could add to your website is one of those news-style tickers that repeats information over and over. If you’re a small business, perhaps you could use such a ticker to display your shop’s hours or address and phone numbers. If you are building a family website, you might add a reminder to your children to do their chores and homework, hoping that repetition will eventually sink in. (Take it from me: It won’t.)

Much of this code has now been present for the past three examples, but there is some new code to discuss here. Within the header, a string variable named scrollMsg is created, and any and all information you want to appear on your ticker is added to the string using the string concatenation operation (+=). Remember that by using this operator, you can add the string listed on the right side of the operator to the end of the string indicated on the left side of the operator. So you can use the concatenation operator to build a string of significant size. A larger scroll of information will keep visitors interested longer. The value to putting the string up in the header is that you can easily find it to change the information as needed, such as a new special of the week or extended hours around the holidays.

The function scrollingMsg follows and takes the completed scrollMsg string and prints it to the created text box, starting with the first character in the string; this happens because the beginPos counter is set to 0 before the function is called. When the string is printed, the beginPos counter is incremented by 1 and then, after a short delay, the function is called again. This time the string is printed in the text box starting from the second character in the string, and the counter is incremented again. Continually printing the string, advanced by a single character, creates a scrolling, animated effect. The function would print the message only once if it weren’t for the if statement that follows the incrementing of the beginPos counter. Each time the function runs, this if statement checks whether the counter is higher than the length of the string. If it is, there’s no more string to print. So the counter is set back to 0, and the rotation begins again, giving the illusion of a never-ending repeating ticker.

The setTimeout() method you used in the photo rotator is used here to scroll the message. Again, the number at the end of the setTimeout() call sets the delay between the function calls, and it therefore sets the speed of the scroll. Again, feel free to experiment with this number to set a pace you feel is right.

Summary

People most often use JavaScript to add fun interactivity to their websites. While many people use existing web-creation tools to add bells, whistles, and widgets to their sites, there is something extremely satisfying about creating the effects yourself. Much of what you learned about Python in the first nine hours can be applied to JavaScript (with some minor syntax changes) to create interactivity and other effects.

The examples presented in this lesson just scratch the surface of what’s possible. You can also use JavaScript to add animation, sound, video, and much more. This book cannot cover it all, but there are numerous other options out there, including Sams Teach Yourself JavaScript in 24 Hours from Sams Publishing.

The next hour covers a few more advanced topics as a JavaScript sendoff before turning to SQL, Visual Studio, and other topics.

Q&A

Q. If one or two of these interactive techniques are good, more would be better, right?

A. Be careful not to overdo interactivity and pizzazz on your website. Too much of it can be distracting and may detract from the look and feel of a professional site. If your site has multiple pages, consider using one or two effects per page and spread them out. Another idea would be to change the interactivity on your page monthly so that it constantly feels fresh and updated. Old content, even if it is interactive, may alienate your visitors. If you don’t seem to care enough about your site to update it, why should they care enough to visit it?

Q. Will these types of effects work if my website visitors view it using a mobile device, like a phone or tablet?

A. Mobile devices have created an additional level of complexity in web development (and more work for web developers!). For now, continue to develop web pages the way you are doing, but as you get more proficient, you should start to consider developing mobile sites as well. When you do, go simple. Some of the best effects on full-page websites do not look good on smaller screens, if they work at all.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What is the advantage of putting image files in the same folder as your JavaScript code?

2. Where do you place a function in the HTML body code if you want it to run as soon as the page loads?

3. What method can you use to repeatedly call a function after a preset delay?

4. What measure of time is used for the delay in the method from question 3?

5. True or false: When you’re working with images, you can only set them up to be interactively clickable.

6. What method would be used to trigger code if a pointer leaves a specific object?

7. True or false: You cannot select the color of the banner around an image.

8. True or false: You can rotate through a maximum of 10 images on a website.

9. What is the difference between onclick() and onmouseover()?

10. How do you add a string to the end of another string?

Answers

1. You don’t have to type the entire file path to your image files if they are in the same file as your program file.

2. Within the <body> declaration, you can add a function with the onload() method, and it will run as soon as the page loads.

3. The setTimeout() method

4. Milliseconds

5. False. You can also set images to be interactive when the mouse pointer hovers over them.

6. onmouseout

7. False. You can change the color of the borders around images.

8. False. There is no limit to the number of images you can rotate through on a website.

9. onmouseover()triggers code when the mouse pointer hovers over a specific object. You must click the object in order to trigger the code if you use the onclick() method.

10. You use the string concatenation method (+=). For example, if you have the string name = "Bobby", and you want to add the last name "Smith" to the string name, you would write:

name += " Smith"

Notice the space before the name Smith in this string. If you didn’t add that, name would equal "BobbySmith".

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

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