Hour 10. Having Fun with Programming

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 with JavaScript can be. Nevertheless, there is more you can do with JavaScript than writing data-processing programs for business and engineering. You can also use JavaScript to jazz up your websites.

The material you master in this hour gives you the 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:

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 you are a business trying to attract customers or someone 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 or delete some pictures as needed. When you declare your array, you first let JavaScript know an element is an image with the new image() function and then you can set the .src for each element in the array to a .jpg image. Again, 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 file names. Adding additional photos 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 your 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 one because before you defined the function, you set i to 0. However, once it sets image1 to famPhotos[0], it now 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 will keep 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 one past the last element of the array, the if statement will automatically reset i to 0 and we can loop through the images in the photo array again from the beginning.

The last line of code, setTimeout, is just a handy JavaScript function that will keep calling your rotator function (and therefore place a new photo on the page), but will wait 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 to not use too small of a number—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 the code function runs as soon as everything is loaded on the page. Within the body, we use a little HTML (which will be covered in greater detail in Hour 16, “HTML5 and CSS3”) to set a heading for the page and a little text before image1 is placed. 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

All images will have the same aspect ratio, so if you mix portrait and landscape pictures, some photos will be stretched to fit the box. So 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 put the product information, such as description and price next to or under the photos, but you could make a cleaner page if the page only had photos and the information would come up if the user clicked on the photo. Again, JavaScript can make it possible thanks to the onclick() method. Within each photo placement line, you can add the onclick() method that runs some chunk of JavaScript code when the user clicks a specific photo.


Tip

The three photos placed on the page each used a different-color border (red, blue, and black). Normally, consistently colored borders would make for a more elegant web design, but this was done to show you the variety of color you can add to your 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. That’s not to denigrate a simple line of information—sometimes, that’s all that you need. However, if you want to present more information, or build a more complex function that executes upon clicking, 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 covered back in Hour 3, “Designing a Program,” 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 the two methods are used in concert to achieve a specific “on and off” effect.


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 put your shop’s hours or address and phone numbers. If you are building a family website, you can 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).

So much of this code has now been present for the past three examples, but there is some new code to discuss. 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 using this operator will 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 scrollMsg follows and takes the completed scrollMsg string and prints it to the created text box starting with the first character in the string thanks to the beginPos counter being 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. By continually printing the string advanced by a single character, a scrolling, animated effect occurs. The function would only print the message once except 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 can begin again, giving the illusion of a neverending 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, therefore setting the speed of the scroll. Again, feel free to experiment with this number to set a pace you feel is right.

Summary

After the first nine hours covered learning basic programming syntax and methodology using JavaScript code as examples, this hour returned to JavaScript’s roots. People most often use JavaScript to add some fun interactivity to their website. While many people use existing web-creation tools to add the bells, whistles, and widgets to their sites, there is something extremely satisfying about creating the effects yourself.

The examples presented in this lesson are just scratching the surface. You can also use JavaScript to add animation, sound, video, and so much more. This book cannot cover it all—there’s additional programming techniques and other languages still to be covered in this book, but there are numerous other options out there, including the previously mentioned Sams Teach Yourself JavaScript in 24 Hours.

That’s not to say you are done with JavaScript—the next hour covers a few more advanced topics as a sendoff on the language before the book turns its attention to Java, OOP, 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 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 that way. 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, is an easy way to 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 come via a mobile device, like a phone or tablet?

A. Mobile devices have led to 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, 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 is the name of the method you can 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: You can only set images 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: There is a limit of 10 images you can rotate through 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 upon the mouse pointer going into the image.

6. onmouseout.

7. False. You can change the color of the border set around images.

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

9. The onmouseover will trigger code when the mouse pointer passes into a specific object. You must click the object in order to trigger the code if you use the onmouseclick image.

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 addition of the space at the beginning of the “Smith” string. If you didn’t add that, name would then equal “BobbySmith”.

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

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