A Web page with images

Images are very important on the Web. A single glance at an image can give users lots of information. They also help set the mood for a site.

You need to know how Webers think about images. What are they for? Where do you get images for a project? What software do you need to have?

That’s what this lesson is about.

You’ll also learn how to manipulate images with jQuery. This is Much Fun. You’ll show them, hide them, resize them, all with animated effects. You can use these techniques to create sophisticated Web 2.0 interfaces.

Finally, you’ll learn how to use JavaScript’s if statement. For example, you might show different images on a page, depending on what language the user speaks. Or maybe different images for different times of day.

By the end of this lesson/page, you should:

This is the last lesson that deals with individual Web pages. Starting with the next lesson, we start working on entire sites.

Onward! To destiny!

What images are for

This page’s goals

By the end of this page, you should:

  • Know what an informational image is.
  • Know what a structural image is.
  • Know the difference between a good image and a bad one.
  • Know what basic image skills you need for Web work.
  • Understand why every Weber needs to have these skills, not just artists.

What are images for?

Images serve three main purposes: informational, interface, and structural. These are not completely separate categories. Some images have multiple functions.

Informational images

Informational images are on a page because they are part of the content of the page. They have meaning, offering information about the page’s topic. If a page is about tractors, an informational image will tell users something about tractors. If a page is about bow ties, an informational image will tell users something about bow ties.

Photographs are the most common informational images. Suppose we’re creating a page about bulldogs. We might add a photo of a bulldog, so users will know what one looks like.

Bulldog

Here’s another example. Let’s say you’re writing a page about making dog biscuits. You have the text:

Quickly stir the mix with a whisk.

You might have a photo to show what a whisk is:

Whisk

The photo contributes to the content, that is, it helps people understand how to make dog biscuits.

CC
CC

Er, won’t everyone know what a whisk is?

Kieran
Kieran

Most people will. But remember two things.

First, some people are new to cooking. Maybe they’re youngsters, just getting started.

Second, people have different names for the same things. Maybe a “whisk” is called something else in Belgium. I don’t know.

Renata
Renata

Where did you get that photo?

Kieran
Kieran

From stock.XCHNG. The photo was posted by the user LittleMan.

Informational images are often photos, but not always. Drawings, maps, screenshots, and other things are informational images as well.

Some informational images convey emotion. Like this.

Awwwww

How you can not look at that and go, “Awwww…”

Interface images

Users click, drag, or otherwise interact with interface images. Here are some buttons:

Button

Button

Button

Button

Structural images

Structural images are part of the visual framework of a Web page. They’re used to separate parts of a page, highlight some areas, and so on.

There are some common types of structural images.

Dividers

Dividers break up sections of a page.

Divider

Divider

Divider

Divider

Bullets

Bullets are often used with list items.

Bullet

Bullet

Bullet

Bullet

Banners

Banners are used for page titles. The ones below are blank. Use a graphics program to add text.

Banner

Banner

Banner

Banner

Are some images better than others?

You need to know what images to use when. Here are some guidelines.

Utility

Informational images should be useful, that is, they should give users information they need. For example, a map that’s too small or too blurry will not help people find your business.

Small map

Mood

The mood of each image ought to fit the message. Here’s a photo that fits the text.

Curious?

Colors

The palette of each image should match the color scheme of your site. We’ll talk more about color later in this chapter.

Screen size

The image shouldn’t be so big that it pushes other page elements out of position. And like the map above, it shouldn’t be so small that it’s useless.

File size

Small is good, as long as you don’t sacrifice too much quality.

People often make mistakes with images from digital cameras. Most images should be shrunk and cropped before they’re shown on a Web page.

This is very important. You, your clients, your employer, could be in Big Trouble if you violate copyright. There are plenty of places where you can get free or low-cost images. If in doubt, find a different image.

Working with images

Every Weber needs to know how to do some basic image tasks.

  • Resize an image.
  • Crop an image.
  • Compress an image.
  • Add text to a photo, with anti-aliasing.
  • Manage an image collection.
  • Create simple drawings.
  • Take screen shots.

We’ll talk about these tasks later.

You should also consider learning how to:

  • Cut out objects from images.
  • Apply filters, like drop shadow and blur.
  • Fix artifacts in photos with dodge and burn.
  • Use layers to combine image objects.
  • Use connectors in drawings.
  • Use a Bézier tool.

Why learn this stuff?

A Weber might say, “I’m a PHP programmer. Other people handle those details. Why should I learn this stuff?”

Again, it’s a matter of employability. It’s a matter of how much value you can create with your Weber skills.

Don’t underestimate the importance of images. Take the CoreDogs page on Web page structure, for example. If you look at it, you might guess there are about eight images on it.

There are about 30.

The + and – in the menu, the arrows on the “My notes” field, the backgrounds for the buttons. They’re all images.

Most images on the Web are simple. You can make almost all the images in an entire site with just a few basic skills. But if you don’t have any image skills at all, you’ll need to call on someone else whenever you need an arrow or a button.

That delays your work. It makes you less productive.

It also means that you can’t take on complete projects by yourself. The Web is a great place for entrepreneurs. You can start your own business, just like I started CoreDogs. But entrepreneurs need to know a little about lots of things. Weber entrepreneurs need to know how to do basic image work.

Learn some basic image skills. It will make you more valuable to clients and employers. And it will come in handy when it’s time to start your own business.

Summary

On this page, you learned:

  • What an informational image is.
  • What a structural image is.
  • The attributes of good images.
  • What basic image skills you need for Web work.
  • Why every Weber needs to have basic image skills.

What now?

Let’s take at look at the three main image formats used on the Web.

How computers show images

Where are we?

You learned that images serve two purposes: informational and structural. You know that it’s important to have basic image skills.

This page starts building those skills by exploring how computers display images.

This page’s goals

By the end of this page, you should:

  • Know what a pixel is.
  • Know how each pixel’s color is represented.
  • Know what a color channel is.
  • Know what anti-aliasing is.

Pixels

Every image on your computer’s screen is made up of pixels. A pixel is a tiny dot of color. When the pixels are small enough, your brain merges them together into a single image.

Here’s an example.

Pixels

Figure 1. Pixels

The photo is of Renata when she was about two months old. Her eye is zoomed by 1,100%, so you can see the pixels.

Images made of pixels are often called bitmaps.

Color codes

Each pixel is made up of three different colors: red, green, and blue (RGB). By mixing different amounts of red, green, and blue, your computer can show any color your eye can see.

The most common way to represent colors in Web work is as RGB codes. Each channel (one for each color) has a number from 0 to 255. 0 means none of the color. 255 means as much of the color as the computer can show.

Why 0 to 255? It has to do with bits, bytes, and powers of two. Really geeky stuff. Let’s decide we don’t care.

Here’s the color (255, 0, 0):

   

Full red, no green, no blue.

Here’s the color (0, 255, 0):

   

No red, full green, no blue.

You can mix colors. Here’s the color (128, 32, 64):

   

So each dot in Figure 1 has three numbers for its color. For example, this color:

   

is in the image. It’s (250, 206, 161).

There are two colors you should know by heart. (0, 0, 0) means all the colors are off. That shows as black, like my fur. (255, 255, 255) means all the colors are on full. That shows as white.

Text and anti-aliasing

Photos have thousands of different colors, captured by a digital camera or a scanner. Text and drawings have fewer colors.

Text

Figure 2. Text

This text has only two colors: white (255, 255, 255) and dark red (157, 16, 16).

But the text is jagged. How about this:

Anti-aliased text

Figure 3. Anti-aliased text

This uses anti-aliasing to make the text look better. Where two contrasting colors meet, the computer works out an average color, and uses that to blend the two together. Anti-aliased images look smoother.

Summary

You learned:

  • That a pixel is a colored dot.
  • There are three color channels for each pixel.
  • That each pixel’s color is represented by an RGB code.
  • That anti-aliasing blends contrasting colors to make color transitions smoother.

What now?

Now let’s see how different file formats store color information.

Image formats

Where are we?

You learned how computers show images on a display. But how they’re stored in files is different. That’s what this page is about.

This lesson’s/page’s goals

By the end of this lesson/page, you should:

  • Know what an image format is.
  • Know the three main image formats used on the Web.
  • Know what transparency and translucency are.

What is an image format, anyway?

It takes a lot of pixels to make a big image. And each pixel needs three different numbers to represent it. The result? Lots of data, and long download times over the Internet, especially for slow connections.

An image format is a way of storing an image in a file. The most obvious format is simply to store all of the numbers for all of the pixels. That’s what a raw image file is, as it comes from the image sensor of a digital camera.

Computerists have come up with clever ways of compressing images, so that they can be stored in smaller files. An “image format” is a way of encoding image data to store in a file.

There are about a bazillion image formats out there. But the vast majority of Web images use only three formats.

The JPEG format

A raw image will contain many more colors than your eye can see. JPEG reduces file size by dropping colors from images, and averaging colors in adjacent pixels.

Let’s be clear what is happening. In the previous lesson, you saw programs like this one for computing a tip at a restaurant:

Get the meal cost from the user.
tip = meal cost * 0.15
total = meal cost + tip
Show tip and total to the user.

This is an algorithm. An algorithm is a set of steps for performing some task. “Algorithm” and “program” mean more-or-less the same thing.

What does this have to do with JPEG?

JPEG stands for the Joint Photographic Experts Group. A bunch o’ dude/ttes got together, and agreed on an algorithm to compress pixel data. They came up with something like this:

Convert from RGB to YCbCr.
Reduce the resolution of YCbCr chroma data.
Split the image into blocks of 8×8 pixels.
...

Got it? No, neither do I. But that’s OK. It works.

So the JPEGers agreed on this algorithm. Then some programmers got to work. They wrote two types of programs.

  1. Encoding programs, that use the JPEG algorithm to encode raw RGB. The encoded data is written to a file, which is smaller than a file with unencoded data would be.
  2. Decoding programs, that read JPEG encoded data from a file, and convert it back into RGB data that the computer shows on the display.

When your Web browser shows a JPEG, it downloads the encoded file from the Internet, decodes it, and gives the decoded data to your computer’s operating system (Windows, OSX, Linux) to show on your display. So your browser has a JPEG decoder built into it, or has one that it can call on.

JPEG files almost always have the extension .jpg.

JPEG is a lossy format, that is, it compresses by throwing away information. Usually that’s OK, because your eye can’t see all of the colors in the raw image anyway. But it can be overdone. Here’s a photo that’s been compressed too much.

Compressed too much

Figure 1. Compressed too much

The good news is that the image file is tiny. Too bad it’s junk.

JPEG is best for photos, that have thousands of colors. Throw some away, and your eye won’t notice.

The GIF format

The GIF format is lossless, that is, it doesn’t throw away information. At least, it tries not to. The trouble is that it limits each image to 256 different colors. The set of colors in an image is called its palette.

That sounds like a lot, and it is for most structural images, like buttons and dividers. But the GIF format is lousy for photographs, which can have thousands of colors.

GIF also has problems with heavily anti-aliased images. As we saw earlier, anti-alias works by adding colors to an image. If an imagine has lots of different color boundaries that need to be anti-aliased, GIF might not be able to handle it.

GIF files have the extension .gif.

The GIF format can do two things that JPEG cannot. One is animation. Here’s an animated GIF.

Animated GIF

Figure 2. Animated GIF

It’s made of a bunch of still images shown in a loop. Here are the frames:

Frame 1

Frame 2

Frame 3

Frame 4

Figure 3. Animated GIF frames

Use animated GIFs sparingly. Many Webers view their overuse as the mark of an amateur.

The other feature that GIF has that JPEG does not is transparency. One of the colors in a GIF image’s palette can be set to transparent. Your GIF decoding software simply skips transparent pixels, not showing them at all. That lets anything underneath show through.

Here’s a GIF of a cow on different colored backgrounds.

Cow
Cow

Figure 4. Transparent GIF

The PNG format

The portable network graphics (PNG) was designed to replace GIF. PNG is lossless, can put thousands of colors in a single image, and supports translucency. PNG does not support animation. PNG files have the extension .png.

I said that PNG supports translucency, while GIF supports transparency (actually. PNG supports both). I’m using the terms in different ways. Not all Webers define them this way, but some do.

A transparent pixel is either all on, or all off. In a GIF image, a pixel is one of the colors from the palette, or it isn’t there are all. The cow in Figure 4 has a transparent background.

A PNG can add an optional fourth channel for each pixel. So there’s a red channel, a blue channel, a green channel, and an alpha channel. The higher the value in the alpha channel, the more of the color is used.

Here’s a flamingo:

Flamingo

Figure 5. PNG flamingo

Here’s a blue spot:

Blue spot

Figure 6. Blue spot

The spot’s pixels get more translucent around the edges the of the spot.

You can see the translucency when you put the spot on top of the flamingo:

Flamingo Translucent circle

Figure 7. Blue spot on the flamingo

This isn’t a different image. It was made by overlaying the two images above.

When the spot’s pixels are not translucent (in the center of the spot), they hide the flamingo’s pink pixels. But when the pixels are translucent (at the edges of the spot), your computer blends the blue with the pink.

Here’s another example. Suppose I wanted a searchlight effect in an ad.

Search for savings!

Searchlight

Figure 8. Searchlight

The pixels in the searchlight have some translucency, so the text underneath always shows through.

The opposite of translucency is opacity. The more translucent something is, the less opaque it is, and vice versa. A translucency of 80% is the same as an opacity of 20%.

Other formats

There are other graphics formats, but they don’t impact the Web as much as the Big Three. We won’t talk about them.

Which format should you use?

Use JPEG for photos, but don’t overcompress. Use PNG for new drawings. There are a lot of existing GIF images you can use on your sites. There’s no need to convert them to PNGs. Just use them as is.

Movies and animation

We’ve been talking about still images. There’s also movies and animation.

The easiest way to show a movie is to upload it to YouTube. Then you can put some code into your page to embed the movie in your site. See YouTube for details.

Flash is the top dog of animation technology. Flash could be a CoreDogs book in its own right. See Adobe’s site to get started with Flash.

Summary

On this page, you learned about the Big Three formats: JPEG, GIF, and PNG. You learned about transparency and translucency.

What now?

Let’s talk about where you can get images for your pages.

Where images come from

Where are we?

You know what images are for (information or structure), that they’re made of pixels and color codes, and that they’re stored in one of the Big Three image formats.

But where do you get images?

This page’s goals

Images come from two source. You make them, or someone else does. By the end of this page, you should:

  • Know how to find images other people have created.
  • Know about different image licenses.

Using other people’s images

Humans have created millions of images you can use on your Web sites. Before you use an image, make sure you understand its licensing terms.

There are many different licenses. In fact, image owners can make up any license they like. For example, a photographer might say that you can only use her images for free on alternate Tuesdays.

But some licenses are more common than others. Here are some samples.

  • “Public domain” means that the image is free for any use, including commercial use.
  • An attribution license means that you can use the image, as long as you say where the image came from.
  • Free non-commercial use means that you can use the image for free on personal and non-profit sites. You may need to pay for commercial use.
  • Paid royalty-free non-exclusive license means that you pay once to use the image on a site, no matter how many people view your site. The “non-exclusive” part means that other mammals can buy a license for their sites as well.

Note that I am not a legal expert. I don’t guarantee anything about this. YMMV.

When in doubt, check. For example, take the paw prints in the header image at the top of this page. I got the image from Dog Paw Print. I didn’t want to follow the exact image terms on the site, so I emailed the site’s owner, asking permission to do something a little different. She wrote back immediately, giving permission.

Let’s look at some image sources.

BurningWell

BurningWell is a collection of public domain photos. The collection is not large, but there’s still a lot of stuff there, and all for free.

morgueFile

morgueFile is one of the better known free photo sites. The images can be used for commercial purposes. The photos are categorized and searchable.

US government photos

Links to various government sites. Most images are in the public domain, but not all.

123RF

This service lets you license images from photographers around the world. Image licenses start from around under $1 per image. You’ll find photos of just about anything here. They have over 4.5 million images at the time of writing.

stockxpert

You can buy images to use on your Web site from $1 each. There’s some great stuff here.

Stock.XCHNG is is part of this family of Web sites. Images can be used for free, with some restrictions. Check the license.

iStockphoto

Like stockxpert. Same parent company, in fact.

More, more, more…

There are hundreds of sites with free or low-cost images. Add your favorites to the links list.

Exercise: Get some dog photos

Find a few dog photos we can use later in this lesson. Make sure they're public domain, or you can use them for free on personal sites.

(Log in to enter your solution to this exercise.)

Creating your own images

Digital camera

Every Weber should have a digital camera, even if it’s just in a cell phone. You never know when you’ll get an opportunity to take a cool photo. And maybe one of your photos will show up on FAIL Blog!

When you buy a cell phone with a camera, make sure there’s an easy way to move images to your computer.

Drawing software

Every Weber should be able to make simple drawings. We’ll talk about that on the next page.

Draw and scan

Robot dog
By zombiecatfire13

That’s where the robot dog came from. Zombiecatfire13 drew it, and said I could add it to CoreDogs.

If you have a dog drawing you did, send it to kieran@coredogs.com. I’ll find a place for it. I’ll link your image to somewhere. Give me the URL.

Summary

There are many sources for free and low-cost images. Make sure you follow license terms. When in doubt, ask.

What now?

Let’s cover some of the tools that should be in your image toolkit.

Your image toolkit

Where are we?

You need to have software to create and manipulate images. Let’s talk about some of the free tools that are available.

This page’s goals

By the end of this page, you should:

  • Know the types of tools you should add to your toolkit.
  • Have downloaded and installed a tool of each type.
  • Be able to complete some basic image tasks.

Image editors

Image editors let you mess with the pixels in images. You can resize, crop, and perform other operations on photos and images.

GIMP is a well-known, powerful, and mature tool. I use it for most of my image work. GIMP is not the easiest to learn. But when you do learn it, you can do anything you want.

GIMP is not a very good drawing tool. Even creating simple rectangles and circles is clumsy with GIMP. But when it comes to cropping, resizing, recoloring, fixing artifacts in photos, and other photo-oriented tasks, GIMP shines.

Paint.NET is another popular tool. Easier to use than GIMP, although less powerful. It can handle common Web image tasks, though some things like dodge and burn are not as easy as they might be.

There are many other free and low-cost image editors out there. Please add your favorite to the links list.

Download and install either GIMP or Paint.NET.

Let’s look at some tasks you might do with these tools.

Cropping a photo

Often you want to focus on just part of something in a photo. Take this one, for example:

Awww

Figure 1. Awww

Maybe we just want the puppy’s head. (In the photo, I mean. You are sick!) So I’ll crop just that part of it.

Suppose I’m using Paint.NET. I’ll open the file, and use the select tool to select the part of the photo I want.

Selecting

Figure 2. Selecting

Now I choose the crop command.

Cropping

Figure 3. Cropping

I end up with a cropped image.

Cropped image

Figure 4. Cropped image

I can save it in a new file, and use it on a Web page.

Resizing a photo

Maybe I want to use the puppy head photo as a small icon. I select Image | Resize from the menu in Paint.NET. I get this:

Resizing

Figure 5. Resizing

The image is 128 pixels wide, and 130 pixels high. I have to be careful to maintain the ratio between width and height. Let’s say I make the new width 90, and the height 40. Here’s what I’ll get:

Squished image

Figure 6. Squished image

Not so good. Fortunately, Paint.NET will maintain the right ratio for me. I just leave “Maintain aspect ratio” checked. This feature is in GIMP, and every capable photo editing program.

I’ll make the image 50 pixels high, and leave the width alone. The software will compute that for me. I end up with:

Puppy icon

Figure 7. Puppy icon

Add text to a photo

Another common task is to add text to a photo. Check I Has A Hotdog! for examples.

Here’s the image I started with:

Renata and ball

Figure 8. Renata and ball

The first thing I did was add a layer. A layer is like a clear plastic sheet on top of an image. You can draw on the layer without messing up the pixels underneath. Layers are important. Every useful tool supports them.

I add the text into the new layer.

Adding text

Figure 9. Adding text

I got:

Meat taste

Figure 10. Meat taste

To make the text look a little better, I added a slight raised effect. I copied the text layer, changed its color, moved it a little, and blurred it a little. This was the result:

Meat taste, raised text

Figure 11. Meat taste, raised text

The difference is subtle, but it’s there.

Exercise: Add a caption to a dog photo

Add a funny caption to one of your dog photos. Crop and resize the photo if you need to first.

If you have an easier way to add text than with Paint.NET or GIMP, let everyone know.

Paste a link to your image below. How? That’s coming up soon.

(Log in to enter your solution to this exercise.)

Image viewers and managers

When you have hundreds of images on your computer, you need some way to quickly look at and manage them. For example, it helps if you can see thumbnails of all images in a directory.

I use IrfanView. Like other viewers, it can perform basic operations on files, like resizing. The thumbnail feature is OK, but buggy.

What’s your favorite? Got any tips? Consider writing an article.

Drawing tools

Drawing tools let you create drawings like this, from the Ajax lesson.

Ajax drawing

Figure 12. Ajax drawing

It combines a photo, screen shots, an icon, text, geometric shapes (the circles around the numbers), and lines with arrows.

Let’s look at a sample task. It will show you some of the features you should look for in a drawing tool. We’ll look at OpenOffice Draw, the program I use with CoreDogs.

I made this image.

Dog happiness

Figure 13. Dog happiness

How?

First, I started with the dog drawing. I got it from WP Clipart, a collection of public domain clip art.

Here’s the original drawing:

Original drawing

Figure 14. Original drawing

There are some artifacts around the dog. Artifacts are errors, extra pixels or changes in pixel colors. They usually result from problems in image scanning or format conversion.

I used GIMP to crop the image and erase extra pixels around the head.

Original drawing

Figure 15. Removing artifacts

Notice that I had zoomed in to 400% so I could work more easily. The broken circle near the top of the image in GIMP’s erase tool.

Once the artifacts were gone, I saved the dog head as a PNG. Then I told Draw to insert it. That’s one feature you’ll need in a drawing program: the ability to insert bitmap files. Recall that a bitmap is an image made of pixels. JPEGs, GIFs, and PNGs are all bitmaps.

Next, I added some text:

Adding text

Figure 16. Adding text

I set the type face to Trebucet MS, the size to 10 pixels, and the color to dark gray.

Drawing programs work differently from photo editors. In editors like GIMP and Paint.NET, everything (most things, anyway) is a pixel, or a bunch of pixels. That makes sense for photos are other images that are pure bitmaps.

In a drawing program, drawings are made up of objects. Objects are things like text, lines, shapes, and bitmap fragments that can be moved, sized, and formatted independently.

When you use a drawing program, you insert and format the objects that make up the image. When everything is right, you create a bitmap version in a JPEG, GIF, or PNG. This is sometimes called exporting the image, or it might be saving in a different format. I actually used screen capture for this step, as we’ll see later.

So far, I have a bitmap object, and a text object. Then I added a connector:

Adding a connector

Figure 17. Adding a connector

A connector is a line that connects other objects. Notice the anchor points, the blur crosses around the text, and the small gray rectangles around the edges of the bitmap’s selection rectangle. I anchored the connector to a point on the text, and a point on the bitmap.

You should look for a drawing tool that supports anchor points. Why? Because you can move objects, and the drawing tool will redraw connectors for you.

Here’s what happens if I move the text.

Moving the bitmap

Figure 18. Moving the bitmap

Now I’ll move the text again, and change the anchor point.

Moving the bitmap again

Figure 19. Moving the bitmap again

The drawing program redrew the curve for me. That’s important! Choose a draw tool with connectors and anchors. It will make your life easier.

Also notice that the connector is a curved line. Curved connectors often look better on drawings with just a few objects. To me, anyway.

Here’s the target image again.

Dog happiness

Figure 13 (again). Dog happiness

Next I added the heart. I didn’t have to draw all of the lines separately. Draw includes a bunch o’ geometric objects: ovals, rectangles, talk balloons, triangles, smiley faces, jewels, jigsaw pieces, ... Each one can be sized, shaped, and colored independently.

Look for a tool that includes geometric objects.

Finally, I added a gradient to the heart:

Adding a gradient

Figure 20. Adding a gradient

You can see from the tabs at the top of Figure 20 that I could have filled the heart with a bitmap, hatching, and other things. Look for features like this in a drawing tool.

Now that I finished the draw, I wanted to put it in a file in one of the Big Three formats. I generally use two of the: JPEG for photos, and PNG for drawings. I created a PNG for this one.

The version of Draw I’m using at the time of writing has trouble with anti-aliasing when it exports drawings. Recall that anti-aliasing reduces jaggies. What to do?

I use screen capture instead. Draw does anti-aliasing fine on the display.

Screen capture

There are many screen capture programs. Two good ones are PicPick and Gadwin PrintScreen. You can capture full screens, the current window, or an area you select with a mouse. Then you can save what you capture into a file.

Exercise: Create a drawing

Create a drawing using bitmaps, text, and connectors (and other object types, if you want). It could be a family tree, instructions for doing something, ... whatever you want.

Use export or screen capture to make a Webable version of the drawing. You’ll use the image soon.

(Log in to enter your solution to this exercise.)

Summary

On this page, you learned about image editors, image viewers, drawing programs, and screen capture programs.

What now?

Now that you have some images, let’s see how we show them on a Web page.

Showing images on a page

Where are we?

You know how to find images for your Web pages, and how to create your own. Now you’ll learn how to show the images on Web pages.

This page’s goals

By the end of this page, you should know how to use the <img> tag to show images.

The <img> tag

Use the <img> tag to show images on a Web page. Like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Happiness</title>
  </head>
  <body>
    <h1>Happiness</h1>
    <p>What makes a dog happy?</p>
    <p><img src="food_love_happiness.png"></p>
  </body>
</html>

Figure 1. Happiness

Give the <img> tag the file to show, in the src attribute, and there it is. You can see the page.

<img> is an inline tag. It usually appears inside a block tag container like <p>.

Relative and absolute URLs

Here’s another version of the same page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Happiness</title>
  </head>
  <body>
    <h1>Happiness</h1>
    <p>What makes a dog happy?</p>
    <p><img src="http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png"></p>
  </body>
</html>

Figure 2. Absolute happiness

You can see this page as well.

You won’t see any difference the way the pages are rendered.

The only difference in the code is at line 10. Let’s look at what’s going on.

Take the version in Figure 2 first. The browser downloads the HTML. It finds the <img> tag, and knows it needs to grab another file from the server. It takes the URL from the src attribute:

http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png

This is an absolute URL, also called a fully-qualified URL. It contains all the information the browser needs to get the image file.

What does the browser do? It contacts the server named in the URLcoredogs.com – and asks for the file /content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png. The server sends the file, and shows it.

Now, let’s look at the same line in Figure 1:

<img src="food_love_happiness.png">

The browser knows that it has to download the file with the image. For that it needs a URL. But the src attribute contains only part of a URL. Where’s the name of the server? Where’s the file path?

When a browser sees a partial URL like this in an HTML page, it does the following:

  1. Take the URL of the page containing the <img> tag.
  2. Strip off the name of the HTML file.
  3. Append the contents of the src attribute.

Let’s see what that does in our case.

1. Take the URL of the page containing the <img> tag.

That would be:

http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/happiness.html

That’s what you’ll see in the browser’s address bar if you look at the page.

Page URL

Figure 3. Page URL

OK, on to the next step.

2. Strip off the name of the HTML file.

The HTML file is happiness.html, so that would leave:

http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/

3. Append the contents of the src attribute.

The src attribute is food_love_happiness.png, so we end up with:

http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png

That’s the complete URL of the image. You can verify this if you copy it and paste it into your browser’s address bar:

Image URL

Figure 4. Image URL

A URL like the one in src="food_love_happiness.png" is called a relative URL, because it’s relative to the HTML page the URL is in. When a browser gets an <img> tag with a URL containing just a file name, it asks the server for a file in the same directory as the HTML file containing the <img> tag.

Webers almost always use relative URLs, not absolute URLs. It makes sites easier to manage. Let’s say I wanted to rename the ClientCore book, and call it BrowserCore. The new location of the image would be:

http://coredogs.com/content_media/lessons/browsercore/web_page_with_images/food_love_happiness.png

If I used an absolute URL, as in this tag from Figure 2:

<img src="http://coredogs.com/content_media/lessons/clientcore/web_page_with_images/food_love_happiness.png">

then the page would be broken. I would have to fix the HTML. No problem for one page, but CoreDogs has hundreds of pages. Ack!

But if I has used a relative URL, like this tag from Figure 1:

<img src="food_love_happiness.png">

I wouldn’t need to change anything, as long as the image file was still in the same directory as the HTML file.

That’s why Webers almost always use relative URLs. They can move files around, without breaking things.

We’ll talk more about relative and absolute tags in the next lesson.

The alt attribute

src is the most important <img> attribute but there are others. One is the alt attribute, which you should add to every image. It gives a text alternative to the tag when the image can’t be shown. The alt tag should describe the image.

The alt attribute is used by screen readers. That’s software used by visually impaired people. As you might guess from the name, screen readers read out the text of a Web page. If the alt attribute is empty, visually impaired users will not know what the image shows. This is particularly important for informational images.

You should use the alt tag for two reasons. First, federal government Web sites in the US must use the alt tag to comply with the section 508 amendment to the Rehabilitation Act of 1973.

Second, pages containing <img> tags without alt attributes do not validate, that is, they don’t comply with the HTML 4.01 standard we use in CoreDogs. If you read about the img tag in the HTML 4.01 standard, you’ll see this:

User agents must render alternate text when they cannot support images, they cannot support a certain image type or when they are configured not to display images.

“User agents” are usually browsers, though there can be more exotic things. Anyway, you can see that the alt tag is required.

Why would you care about this? Because search engines prefer pages that validate. And that makes your pages easier to find.

Exercise: Showing your drawing

You created a drawing in a previous exercise. Now create an HTML page that shows the image. Use a relative URL.

Upload the image and your HTML page to your server. Put the URL of the page below.

(Log in to enter your solution to this exercise.)

Summary

  • Use the <img> tag to show images.
  • You can use relative or absolute URLs, though you should use relative URLs most of the time.
  • Use the alt attribute to give a text alternative for each image.

What now?

Now you know how to show an image on a page. Let’s see how you can style image boundaries, like add a color border.

Styling boundaries - the box model

Where are we?

You know how computers represent images. You know how to find free images, and show them on page. Let’s use CSS to add some styling to image boundaries.

This page’s goals

By the end of this lesson/page, you should:

  • Know what the box model is.
  • Be able to style image and text boundaries.

The box model

As you know, the <p> tag puts white space around text. For example:

<p>This is a paragraph.</p>
<p>This is a not a paragraph. Oh, wait, yes it is.</p>

Without styling, this looks like:

Paragraphs

Figure 1. Paragraphs

There is white space above, below, and to the left and right of each paragraph. But how does the browser decide how much white space?

Let me ask another question. Why is the text in Figure 1 black? You learned that it’s black because that is the browser’s default, when you don’t use a style. Why is the background white? Same reason. Why use a serif typeface? Same reason.

So, how does the browser decide how much white space to use around <p>s? Same way. The browser has defaults that it uses, unless you tell it otherwise.

Each block tag, like <p> and <hx>, is inside a box. The box has a border (usually invisible) and white space. You control the box by using the CSS attributes border, margin, and padding.

The box model defines how box around a block tag is created. Let’s look at it.

Let’s start with the most fun part, the border.

The border attribute

You have lots of control over the border around an element.

Border style

Here’s a picture of me in the snow, with a solid border.

Solid border

Here’s the code:

.solid_border {
  border-style: solid;
}
...
<img class="solid_border" src="kieran_snow.jpg">

Here’s a dashed border:

Dashed border

Here’s the code:

.solid_border {
  border-style: dashed;
}

The default style is hidden.

There are more styles, like dotted and grooved. You can see the list at SitePoint.

There are four borders around the image. You can give each border a different style. For example:

Mixed border

Here’s the code:

.mixed_border {
  border-top-style: solid;
  border-right-style: hidden;
  border-bottom-style: groove;
  border-left-style: dotted;
}

It looks terrible, but it shows you the options.

You can put the values on one line, like this:

.mixed_border {
  border-style: solid hidden groove dotted;
}

How does the browser know which style to put on each side? It goes in the order top, left, bottom, right. That’s in clockwise order from the top:

Border order

Figure 2. Border order

This ordering applies throughout CSS. For padding, margins, and other things we’ll see later.

Border width

You can set the width of borders like this:

Thick border

.thick_border {
  border-style: solid;
  border-width: 10px;
}

The width won’t show unless you set a style as well.

Border color

Set a border color using the usual color codes, the same ones used for fonts and everything else. For example:

Green border

.color_border {
  border-style: solid;
  border-width: 10px;
  border-color: #668014;  
}

Combining into one border style

Usually when I set colors, I specify color, style, and width, and want them the same for all sides. There’s a shortcut for that:

.color_border {
  border: solid 10px #668014;  
}

This is what I normally do for borders. Put all the options in a single border style. Simple is Good.

Margins and padding

We’re talking about the box model. We’ve talked about borders. Another attribute, margin, let’s you control the spacing around an element.

Suppose I had this HTML:

<p>
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg"><br>
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg"><br>
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg">
  <img src="kieran_snow.jpg">
</p>

Figure 3. Dog matrix code

It renders like this:

Dog matrix

Figure 4. Dog matrix

The gap between the images is because of the white space characters in the HTML: the spaces and new line between each imate.

I’ll change one of the lines to this:

<img class="big_margin" src="kieran_snow.jpg">

Now I’ll add a class:

.big_margin {
  margin: 20px;
  border: dotted 2px #668014;
}

Here’s what I end up with:

Dog matrix with margin

Figure 5. Dog matrix with margin

Notice how there’s space between the border and the other elements around the image. That’s what the margin property does.

The padding property also adds a gap, but it’s a little different. Here’s a style:

.big_padding {
  padding: 20px;
  border: dotted 2px #668014;
}

Dog matrix with padding

Figure 6. Dog matrix with padding

The padding attribute adds a gap between the edge of the content and the border. That’s different from margin, which adds the space outside the border.

You can use them both together.

.big_margin_padding {
  margin: 20px;
  padding: 20px;
  border: dotted 2px #668014;
}

It looks like:

Dog matrix with margin and padding

Figure 6. Dog matrix with margin and padding

Text, too.

You can use the same properties with text. For example, let’s say you want to make a message stand out, like this:

Text standing out

Figure 7. Text standing out

Here’s a page that does this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>The Dog Zone</title>
    <style type="text/css">
      body {
        font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
        font-size: 14px;
      }
      .stand_out {
        border: dotted 2px red;
        background-color: #FFB6C1;
        font-weight: bold;
        font-style:italic;
        margin: 20px;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <h1>The Dog Zone</h1>
    <p>Welcome to the best place for dog fun on the Web.</p>
    <p class="stand_out">Today only! 50% off road kill!</p>
    <p>Get your stuff here!</p>
  </body>
</html>

You can try the page, if you like.

Summary

Browsers render elements with defaults for border, margin, and padding. For instance, the default border is hidden, meaning no border is visible. You can change them all with CSS.

What now?

Another neat thing you can do with images is use them as backgrounds, for entire pages, or for individual elements. Let’s see how.

Background images

Where are we?

You know how to add images to a page, and put boundaries around them. Let’s see how you can put images into the background of a page.

This page’s goals

Background images can give a nice look to your pages. Usually they’re used to set a mood. Backgrounds can be set for entire pages, or for parts of pages.

By the end of this page, you should:

  • Be able to add a single image background.
  • Be able to add a tiled background.

Using one large image

You can use one large image to set a mood, as seen on this page. This might a page on a landscaping site, or one about nature vacations. The image has a relaxed, natural feel.

I didn’t want the image to interfere with the text, so I put it in the upper right of the page, and made it fade out fairly quickly.

Let’s see how I created the effect. I started with a larger version of this photo I took at a local park:

Scenery

Figure 1. Scenery

I used Gimp to add a transparency mask, a black-and-white overlay that tells Gimp what part of the image shows through. You can see how it works:

Transparency mask

Figure 2. Transparency mask

You can see the mask to the right of the photo. Imagine that it’s dropped on top of the photo. White areas in the mask let the photo show. Black areas block the photo from showing. When the photo is blocked, the background underneath shows. It’s a simple white background in this case, but it could be another color, a texture, a different photo, ... whatever your imagination can conjure.

The mask uses a gradient, that is, the mask’s color gradually changes from white to black. When there are gray pixels in the mask, Gimp combines the color from the photo with the background layer’s color. The more white there is, the more of the photo’s color is used.

Here’s a small version of the result:

Background image

Figure 3. Background image

You don’t have to know how to do photo work like this yourself, if you have someone to do it for you. But it helps to know in general terms how graphics people do their work. Using transparency masks is a common technique.

Now that I have the image, I want to put it in the upper right of the page. Here’s the entire page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Full image background</title>
    <style type="text/css">
      body {
        background-image: url('scenery_back.jpg');
        background-repeat:no-repeat;
        background-position:top right;
      }
    </style>
  </head>
  <body>
    <h1>Full image background</h1>
    <p>This is a sample page with a background image.</p>
  </body>
</html>

Figure 4. Page with a background image

Notice that the image is added in the CSS, not in the HTML. Because the rule is attached to the body, the image will be behind the entire page.

The first part of the rule tells the browser where the image is:

background-image: url('scenery_back.jpg');

The browser looks for the image in the same directory as the style sheet. The next lesson explains how to make URLs point to different places.

The image file I made is 640 pixels wide and 480 pixels high. Your computer’s display is bigger than that, maybe 1024 pixels wide and 768 pixels high. What happens?

By default, the browser repeats the background image until it fills up the entire display. I just wanted one copy of the image. So, I added this to the CSS:

background-repeat:no-repeat;

Finally, I wanted the image at the top right of the page. Hence the rule:

background-position:top right;

A tiled background

Sometimes you want a page to look like it was written on paper, chiseled in stone, printed in the sky, or whatever. Have a look at the Make ‘em proud theme. The background image is yellow with dark flecks, giving the impression of old paper.

This type of effect uses a tile. A tile is a small graphic that looks good when it’s repeated. The edges fit together seamlessly.

Here’s a tile from GRSites.com:

Background tile

Figure 5. Background tile

Here’s what it looks like when used as a background:

Hi there!

This is a tiled background. Notice how the edges of the tile are seamless?

There are a bazillion seamless tiles you can use for free, or you can make your own.

We now return you to your regular background.

Figure 6. Using the tile

The CSS rule is something like:

.tiled {
  font-size: 20px;
  color: white;
  padding: 20px;
  background-image: url('tile.gif');
}

Figure 7. CSS rule for tiled background

There is no background-repeat style. The browser’s default is to repeat across and down the tiled area, filling it completely. This is what we want.

Some tiles use part of the image to represent specific objects. They can be a bit tricky to use well, but give nice results.

This example uses another background from GRSites.com:

Hi there!

This is another tiled background. The edges are seamless as well.

The <p>s on top of the background have some extra padding on the left. This looks like the text was indented a bit to avoid the left margin.

We now return you to your regular background.

Figure 8. Using the tile

A rule for this would look something like:

.notepaper {
  font-size: 16px;
  color: black;
  padding: 20px 20px 20px 100px;
  background-image: url('paper_background.gif');
  background-repeat: repeat-y;
}

Figure 9. CSS rule for notepaper background

The padding style uses the same ordering shorthand we saw earlier: clockwise from the top (top – right – bottom – left). The background-repeat is set to repeat-y. This repeats the image down the page, but not across.

To see what this means, I’ve taken another paper background image from GRSites.com. Please have a look.

The image is 800 pixels wide. That’s not as wide as most displays these days, which start around 1,024 pixels. So what does the browser do when with it runs out of background image?

To see what it does, I’ve cropped the background image to 300 pixels:

Cropped tile

Figure 10. Cropped tile

(I added the border so you could see how big the image is.)

Here’s what it looks like without any control over the repeating:

Hi there!

This is another tiled background.

It's been cropped to 300px wide.

We now return you to your regular background.

Figure 11. Using the cropped tile

Remember, the browser’s default action is to repeat background images. This tile is designed to repeat in the y direction (down the page), but not in the x direction (across the page). So I need to add background-repeat:repeat-y; to the CSS rule, so that it only repeats down the page, but not across. Here’s the rule:

.notepaper {
  font-size: 16px;
  color: black;
  padding: 20px 20px 20px 100px;
  background-image: url('paper_background4_cropped.gif');
  background-repeat: repeat-y;
}

Figure 12. CSS rule for with background-repeat:repeat-y;

Here’s the result:

Hi there!

This is another tiled background.

It's been cropped to 300px wide.

This time, I've used background-repeat:repeat-y; in the CSS rule. Hooray!

We now return you to your regular background.

Figure 13. Using the cropped tile with background-repeat:repeat-y;

Ahhhh… Much better.

Summary

On this page, you learned how to add background images to a page. You learned how to add a single image, and tiles. You learned how to use background-repeat:repeat-y; for tiles that are designed to repeat vertically only.

What now?

We’re getting close to the end of the lesson. The next lesson starts putting everything together to let you create entire Web sites.

But we want to be able to do some cool, Web 2.0 stuff with images. Let’s use jQuery to mess with images.

W00f!

Colors and color schemes

Where are we?

You need to create the right look and feel for your Web site. You learned about typography. Now let’s talk about color.

These ideas apply to both text and images. Text color is set with CSS. Image color is part of the images themselves.

This page’s goals

By the end of this page, you should:

  • Know what a color scheme is.
  • Know how to describe individual colors.
  • Know about different types of color schemes, like monochrome and analogous.
  • Be able to decide what you want from a color scheme.
  • Be able to extract a color scheme from a photograph.

The goal: A color scheme

Our goal is to create a color scheme for a Web site. A scheme is a set of a few colors. It’s often called a palette.

Here are some samples:

Color schemes

Figure 1. Color schemes

These color schemes are from Colors on the Web, a site that has schemes, a color wheel, a contrast analyzer, and other things.

We want a scheme that is usable and aesthetically pleasing.

  • Usable – can the visitor read the content comfortably?
  • Aesthetics – do the colors invoke the right mood?

Colors in CSS

This page is not about CSS. It’s about color. But eventually, you’ll need to make your color choices into something you can use in CSS.

Recall that colors in CSS are usually represented as three numbers: the amount of red, green, and blue that make up a color. Each number is from 0 to 255. You can set colors using the three numbers, like this:

color: rgb(128, 0, 0);

Or you can use a hexadecimal value:

color: #800000;

rgb(128, 0, 0) and #800000 are different ways of saying the same thing. Use whichever is more convenient. For example, the schemes from Colors on the Web in Figure 1 give you hexadecimal numbers. To use one of them, copy-and-paste the hexadecimal numbers.

The rest of the page

This page will help you create a GECS, a Good Enough Color Scheme. It may not win any art awards, but it won’t embarrass you, either.

Before I show you how to make a GECS, we need to have some good words for talking about colors. RGB codes are fine for computers, but that’s not the way people think about about color.

Let’s start by finding good ways to talk about:

  • Individual colors
  • Relationships between colors

Describing individual colors

When you’re working with a client on a Web site’s colors, talking about RGB codes won’t get you very far. But you can use words like “intense blue,” “bright green,” and “washed out orange.” Let’s see if we can come up with some ways of talking about colors that are precise, but also make sense to regular people.

HSV is an alternative to RGB. As in RGB, a color is specified by three numbers. But the numbers mean different things. They mean Hue, Saturation, and Value.

Hue is what we normally mean by “color.” Red, green, orange, violet, ... they are hues. The color wheel captures them. Here is a color wheel:

Color wheel

Figure 2. Color wheel

There are many different kinds of color wheels. This one is the color wheel that GIMP uses. The primary hues – red, green, and blue – are as far apart as they can get on the wheel.

Primary hues

Figure 3. Primary hues

As you move around the wheel, from one primary hue to another, you start mixing hues:

Mixing hues

Figure 4. Mixing hues

When you have an equal amount of two primary hues, you get a secondary hue, like yellow, that looks entirely different from both of the primaries:

Secondary hue

Figure 5. Secondary hue

So the first part of an HSV color is the hue.

You may say to yourself, “Self, there are lots of colors missing. Where’s the dark green of the leaves on my favorite tree?” Your self is right. Give he/she/it a cookie.

This is where the other two parts of HSV – saturation and value – come in. Saturation is the intensity of a color. Value is how bright the color is.

I had a hard time figuring out what saturation and value actually meant until I saw a chart like this one.

Saturation and value

Figure 6. Saturation and value

This shows the pure red hue with different amounts of saturation and value. The color that is the most red (in the upper right) has high saturation and value. A pastel red (that is, pink) has low saturation, but high value – low intensity, high brightness. Dark red (looks like brown) has medium intensity and value.

If you have a good natural sense of color, your probably understand what saturation and value are by now. If you grok (“get it”), you can skip down a few paragraphs to the tints and shades section.

But I have to admit, I don’t have a natural sense of color. I needed to do some more thinking before I figured out HSV.

Here’s the way I think of it. The column on the left gives you a base amount of brightness to work with. For the grays in the left column of Figure 6, the amount of red, green, and blue is all the same. That’s what makes gray. The more of each color there is, the brighter the gray gets.

Grays

Figure 7. Grays

You get to white when red, green, and blue reach 255, their maximum value.

Renata
Renata

Is there anything special about those numbers, 215, 175, 135, and so on?

Kieran
Kieran

No. I wrote a program to create the display in Figure 6. The program just happened to end up with those numbers, when it had made an image I liked.

Nothing special about the numbers, except for 255. That’s the maximum for a color. The minimum is 0. rgb(0, 0, 0) is black – no colors at all.

Let’s pick a row from Figure 6:

Value and hue constant

Figure 8. Value and hue constant

The value is all the same in the row. The colors are equally bright. As we increase the red saturation, the ratio of the amount of red to the amount of green and blue gets bigger and bigger. But the colors remain dull, because they all have the same brightness.

Tints and shades

The colors on Figure 6 are all tints and shades of red. You get a tint of a color if you add white to it. You get a shade of a color if you add black to it.

Tint and shade

Figure 9. Tint and shade

The bottom line

For me, color is hard to think about. Maybe my brain is just not wired that way. But I know people who have no trouble with it.

What to do when you’re talking to, say, a client about color? Have some charts like Figure 6 handy. Then you can say, “These are all reds, but different kinds of reds.”

More on this later.

Describing the relationships between colors

We can describe a color by talking about its hue (base color), saturation (intensity), and value (brightness). But that’s only half the story.

A color scheme is not just one color. It’s a bunch of colors that work together to create an overall effect. We need a way to talk about collections of colors.

We’ll describe color schemes by how they use the color wheel. You saw a color wheel earlier.

Color wheel

Figure 2 (again). Color wheel

The wheel shows different hues.

You can make color schemes based on the color wheel. I’ll talk about few different types of color schemes.

Monochrome with accent color

A monochrome scheme is a set of tints and shades of one hue. Recall that a tint is a hue (like red) mixed with white. A shade is a hue mixed with black.

Monochrome schemes don’t have to be black-and-white (although they can be). Here is a monochrome scheme from Color Scheme Designer:

Color Scheme Designer

Figure 10. Monochrome scheme

The base color is in the middle. Tints and shades surround it.

Usually a monochrome color scheme by itself is not enough for the Web. You’ll need an accent hue, used to highlight things you want to draw people’s attention to. Like a special offer. Use accents sparingly.

Here’s a black-and-white monochrome scheme, from Khoi Vinh’s Web site:

Monochrome site

Figure 11. Monochrome site

What a handsome fellow! Reminds me of someone. Hmm…

When you put the mouse cursor on an article name, you see an accent color:

Accent

Figure 12. Accent

If you need more than one accent color, consider making them tints and shades of the same hue.

Here is a monochrome design based on blue, with an orange accent:

Blue monochrome

Figure 13. Blue monochrome

I cheated a bit on this one. The actual design has some fish and things, to punch it up a bit. You’ll see that later.

Since black, white, and gray are neutral, any hue will stand out, and can be an accent color. But when a monochrome scheme uses a different base color, like the blue in Figure 13, you have to be more careful. Try using an accent hue that’s directly opposite on the color wheel:

Accent color for blue

Figure 14. Accent color for blue

This is exactly what’s happening in Figure 13.

Two hues are complementary if they are directly opposite each other on the color wheel. They have high color contrast.

If you use a bright, low saturation color for a background, most dark colors can be accents, even if they are not complementary. Here’s an example from Winnie Lim’s site:

Accent color for bright, low saturation background

Figure 15. Accent color for bright, low saturation background

Most of the page uses shades and tints of brown. The dark red makes a nice accent. It’s not opposite brown on the color wheel, but it looks OK because the background is pastel (bright, with low saturation).

Notice the picture of the dogs. It uses different colors entirely, and adds visual punch to the page. This is an accent object, something that stands out.

Here’s another example of fishy accent objects. The page in Figure 13 actually looks like this:

Accent objects

Figure 16. Accent objects

The yellow-orange color of the accent objects is complementary to the basic blue of the site. The fish automatically draw the viewer’s attention.

Complementary color schemes

We just saw a monochrome scheme with an accent color. The accent color might be the complement of the base color, that is, opposite on the color wheel.

Suppose you use the opposite color not just to accent the occasional element. You can use it as one of the main colors on the site. Then you get a complementary color scheme.

Complementary schemes creates a high-energy, vibrant look. They feel different from monochrome schemes, which are more plain.

Some reds and greens are complementary:

Red and green

Figure 17. Red and green

Here’s a site that uses them:

Complementary scheme in action

Figure 18. Complementary scheme in action

This page uses tints and shades of green and red.

Analogous with an accent hue

Analogous schemes use colors that are close to each other on the color wheel. They are more peaceful, less jarring than complementary schemes.

Here’s an example from Arcion, a company that, among other things, sells complete Web site templates.

Analogous scheme

Figure 19. Analogous scheme

As before, you can use a color from the opposite side of the color wheel as an accent hue. Tints and shades of red might work well.

Other schemes

There are triadic, rectangle, square, and other schemes. The names are based on how the schemes use the color wheel.

We’ll just stick with the three we have:

  • Monochrome
  • Complementary
  • Analogous

TigerColor’s color harmony page explores other types of schemes.

Creating a GECS

As you can see, color is a complicated topic. So what do you actually do in a real Web project?

This section explains how you can make a GECS. GECS stands for Good Enough Color Scheme.

The general approach is to:

  • Understand what you want.
  • Use something that somebody else has created.

You could just use somebody else’s color scheme, or you could use a complete design that has the colors you want.

Of course, don’t go stealing things willy nilly. Use color schemes and designs that you have permission to use. Use things that are free, or buy the right to use them.

Let’s start with the first step.

Know what you want

Often, you aren’t entirely free to choose colors. Your client or employer might already have some standard colors. For example, IBM isn’t called Big Blue for nothing.

If there isn’t a standard color set, there may be a logo that you must use. There might also be product photos or other graphic objects that you must include.

If you have to match a photo’s colors, there are tools that can help. They will analyze a photo, and create a color scheme based on it. You can use the scheme directly, or modify it to meet your needs.

One tool is Whats its color. You can upload a photo, or enter the URL of one. Give it a try.

If your client has any of these things (standard colors, a color logo, product photos, etc.), these colors are the beginning of your color scheme.

Now list some words to describe the mood you want from the site. “Serene” and “peaceful” might suggest blues and greens in a analogous scheme. “Lively” and “fun” suggest something else.

Now pick a few colors (including accent colors). Play with tints and shades. You won’t stay with these, necessarily. They’re a starting point.

There are many fun tools to play with. Sharebrain has a nice list of color tools. Check it out.

The goal here is not to settle on a color scheme, but to understand what you want. If you don’t know what you’re looking for, how are you going to choose the right thing?

So look at the logos, think about the site’s mood, and play around for a while. Then, when you see something that fits, you’ll recognize it.

Look at color schemes

Now take a look at some color schemes that other people have created. There are three options here:

  • Look at color schemes only
  • Look at complete designs
  • Sample existing pages and images

There are many color scheme galleries. I mentioned Colors on the Web earlier. Color Schemer is another one.

Another good option is to look at complete designs, that include colors and graphics. One of my favorite sources is Open Source Web Design. Here are some of their offerings:

OSWD designs

Figure 20. OSWD designs

It helps to know roughly what you’re looking for before looking at a design gallery.

A third choice is to base your colors on something that already exists, either a Web site or an image. There are tools that will help.

ColorZilla is an add-on for FireFox. When you install it, it adds an eyedropper to the Firefox status bar:

ColorZilla

Figure 21. ColorZilla

Click it to sample any color in the browser window.

The real fun starts when you right-click, and start the color analyzer.

Starting the color analyzer

Figure 22. Starting the color analyzer

ColorZilla will analyze the page, and give you the color scheme:

The color analyzer in action

Figure 23. The color analyzer in action

Choose a scheme

You have thought about what you want, played around with some color schemes, and looked at some alternatives. Choose the scheme you will use. If you’re creating a site for someone else, ask them to approve your choice before you invest too much time in graphics and such.

Summary

  • You want to choose a color scheme, a set of colors that work together.
  • Individual colors have a hue (basic color), saturation (intensity), and value (brightness).
  • A tint is a color with white added to it. A shade is a color with black added to it.
  • Types of color schemes include monochrome with an accent color, complementary, and analogous with an accent color.
  • You need to understand what you want before choosing a color scheme.
  • You can download complete designs, that include colors and graphics.
  • You can generate a color scheme from a photo.

What now?

Let’s move on to learn a few more details about graphics.

Graphics

Where are we?

We’re talking about the look and feel of a Web site. You’ve learned about typography and colors. Now for the last component: graphics.

This page’s goals

In this page, you will learn that:

  • Informational graphics are part of a page’s content.
  • Interface graphics are things like buttons that people click on.
  • Structural graphics are part of the visual framework of a Web page.
  • Graphic elements should conform to the color scheme you have chosen.
  • You can use a jQuery plug-in to make rounded corners.
  • Packaged designs include layouts and graphics, already made.

Images versus graphics

Most of what you need to know was covered in the lesson a Web pages with images. This page reminds you of some stuff, and adds a few extra thoughts.

I’m using the terms “images” and “graphics” a little differently. Images are photos or drawings, stored in files in JPEG, PNG, or some other formats.

Graphics is a broader term. It includes images, but it also includes borders, shading, lines, and other effects, that are created by HTML and CSS. Like <hr> and border: 1px solid black;.

CC
CC

Does everyone use the words “images” and “graphics” the same way you do?

Kieran
Kieran

No. Most Webers use “image” the same way I do. But the word “graphics” means different things to different people.

I define it the way I do for ease of learning.

Color schemes

You learned about color schemes on the previous page. Graphic elements should conform to the color scheme you have chosen. So if you’re using, say, an analogous green-blue scheme with orange for accents, the graphics on the site should use that same scheme.

The exception to this is when you use photos of real objects. Photos of people, locations, products, ... the colors are what they are.

Layout graphics

Recall that layouts break pages into regions:

Regions

Figure 4. Regions

You want to give visual cues that the regions exist. Figure 4 uses borders, background colors, and whitespace:

Layout cues

Figure 5. Layout cues

What does CoreDogs use? Have a look at the regions to the right. They are separated with whitespace, and a faint gray border. The CSS for the border is:

border-left:1px dotted #E1E1E1;

E1E1E1 is a hexadecimal code for the three colors: red, green, and blue. Each of them has the value E1, which is 225 in decimal. In CSS, #E1E1E1 is the same as rgb(225, 225, 225).

Remember that when red, green, and blue all have the same value, the result is gray. 225 is a high value (the maximum is 255). The color is fairly close to white, so we get a light gray.

Rounded corners

It’s fairly common these days to see rounded corners on Web sites. For example:

Rounded corners in action

Figure 6. Rounded corners in action

There are lots of ways to do this, some of them quite complex. Fortunately, our good old friend jQuery makes it easy. There are several jQuery plug-ins that will round corners. We’ll use jQuery Corner.

Suppose you wanted to create a region like this:

Rounded corners effect

Figure 7. Rounded corners effect

You could use the code below. You can try it here.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Rounded Corners</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://coredogs.com/resources/jquery.corner.js"></script>    
    <script type="text/javascript">
      $(document).ready(function() {
        $(".truth").corner();
      });
    </script>
    <style type="text/css">
      .truth {
        background-color: #ffd0ff;
        margin: 10px;
        padding: 10px;
        width: 150px;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div class="truth">
      <p>Dogs are the best!</p>
    </div>
  </body>
</html>

Figure 8. Code to round corners

Let’s take a look at the code.

Since it uses jQuery, we need to include the jQuery library as usual. That’s on line 6.

Line 7 includes the plug-in. It’s in the CoreDogs resources directory. You can just copy-and-paste this line into your own projects, if you want.

Lines 24 to 26 create the HTML element we want to style:

<div class="truth">
  <p>Dogs are the best!</p>
</div>

Figure 9. Element to style

It’s just a <div> with some stuff in it. We used <div>s to create regions when learning about page layout.

Here’s some CSS that styles the <div>:

.truth {
  background-color: #ffd0ff;
  margin: 10px;
  padding: 10px;
  width: 150px;
  text-align: center;
}

Figure 10. CSS for the truth

Line 15 sets the background color. Lines 16 and 17 add some whitespace. Line 18 limits the width of the <div>. Line 19 centers the content.

Put the HTML in Figure 9 with the CSS in Figure 10, and they will create this:

Square corners

Figure 11. Square corners

But that’s not what we want. We want:

Rounded corners effect

Figure 6 (again). Rounded corners effect

That’s what the jQuery plug-in does for us. We tell jQuery to use the corner() function on all the things we want to round:

$(document).ready(function() {
  $(".truth").corner();
});

Figure 12. jQuery code

$(".truth") means “find all the things with a class of truth.” Then call corner() on all of them. corner() is defined in the plug-in.

The plug-in can change the corner shape, give different corners different shapes, change the size of the rounding, and lots of other things. See the plug-in’s demo page for examples.

Using packaged designs

Remember that there are packaged designs you can use. You can get them from Open Source Web Design, and lots of other places. They include graphics that are already matched to the site.

Summary

  • Informational graphics are part of a page’s content.
  • Interface graphics are things like buttons that people click on.
  • Structural graphics are part of the visual framework of a Web page.
  • Graphic elements should conform to the color scheme you have chosen.
  • You saw how to use a jQuery plug-in to make rounded corners.
  • Packaged designs include layouts and graphics, already made.

What now?

Time to design a framework for your personal site.

Changing images - jQuery and the if statement

Where are we?

You know how to show an image on an HTML page. But the image doesn’t have to just sit there. You can hide images, show them, change their size, and other stuff.

This page’s goals

By the end of this page, you should:

  • Be able to show and hide images based on events.
  • Understand how a basic if statement works.

Review: Showing and hiding text

In the previous chapter (A Web page that interacts), you learned how to use JavaScript to show and hide text. Let’s look at example to refresh your memory.

Let’s create a Web page with a dog riddle. The question is shown to start with:

Dog joke start

Figure 1. Dog joke start

Click the text that says “Click to show/hide the answer,” and you see:

Dog joke answer

Figure 2. Dog joke answer

You can try the page.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Dog Joke</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#answer").hide();
        $("#toggle_answer").click(function() {
          $("#answer").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Dog Joke</h1>
    <p>What do you get if you cross a Red Setter with a Pointer?</p>
    <p id="toggle_answer">Click to show/hide the answer</p>
    <blockquote id="answer">A Pointsetter, the Christmas dog.</blockquote>
  </body>
</html>

Figure 3. Dog joke code

Remember that an event is something that happens. The ready() event happens when a page has been loaded. Lines 9 to 12 are run when the page has been loaded, but just before it is shown to the user.

Line 9 hides the answer to the riddle. Lines 10 to 12 set up the the click() event for the thing with the id of toggle_answer (don’t forget the # to tell the browser to look at the id attribute). When toggle_answer is clicked, toggle the visibility of the thing with the id of answer.

Showing and hiding an image

You can do the same thing with an image. Let’s create a page with a button on it that shows and hides a picture of a puppy. It will start like this:

Show puppy start

Figure 4. Show puppy start

Click the button, and you see:

Show puppy start

Figure 5. Show puppy end

You can try the page.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Cute Puppy</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show/hide puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 6. Show puppy code

The JavaScript is the same as before. The only thing that’s changed is the object that’s being show and hidden. It’s puppy_container.

Note how I named it. puppy_container is a <p> tag that contains the <img> tag that shows the image.

Exercise: Show and hide your drawing

Remember that drawing you created? Create an HTML page with a button that shows and hides that drawing.

Upload to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Changing the button caption

For our next trick, let’s change the button’s caption in the puppy show program. The button says “Show/hide puppy.” Let’s make it say “Show puppy” or “Hide puppy,” depending on whether the photo is showing or not.

The page will start like this:

Show puppy, simpler button

Figure 7. Show puppy, simpler button

Press the button, and get:

Nice puppy!

Figure 8. Nice puppy!

You can try the page.

Notice that the text on the button has changed. So, both the image and the caption switch back and forth between two states. When the image is not showing, the caption says “Show puppy.” When the image is showing, the button says “Hide puppy.” When the user clicks the button, both the image and the button change.

To show and hide an image, there’s the handy toggle() function. Toggle does some work for us. If the thing being toggled is showing, toggle() hides it, and vice versa.

There is no built-in function for toggling button captions. We have the handle the change ourselves.

First, I’ll work out the logic. I’ll write pseudocode.

When the button is clicked:
  Get the button caption
  If the caption is "Show puppy"
    Make the caption say "Hide puppy"
  If the caption is "Hide puppy"
    Make the caption say "Show puppy"
  Toggle the image

Figure 9. Pseudocode for the button click

Click the button, then click again, then click again, then click again, and the button’s caption will go back and forth between “Show puppy” and “Hide puppy.”

Let’s write it in JavaScript.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Cute Puppy</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#puppy_container").hide();
        $("#show_hide_puppy").click(function() {
          var button_caption = $("#show_hide_puppy").text();
          if ( button_caption == "Show puppy") {
            $("#show_hide_puppy").text("Hide puppy");
          }
          else {
            $("#show_hide_puppy").text("Show puppy");
          }
          $("#puppy_container").toggle('slow');
        });
      });
    </script>
  </head>
  <body>
    <h1>A Cute Puppy</h1>
    <p><button id="show_hide_puppy" type="button">Show puppy</button></p>
    <p id="puppy_container"><img src="renata_young.jpg" alt="Cute puppy"></p>
  </body>
</html>

Figure 10. Toggling the button’s caption

Getting text

Line 11 is:

var button_caption = $("#show_hide_puppy").text();

This will get the current value of the button caption, and put it into the variable button_caption. Then we can test it.

This is a different use of the text() function. Earlier, we used text() to set the text in something, like this:

$("#best_color").text("Green")

This put the text Green into the thing with the id best_color.

You can also use text() to get the text in something. That’s what happening in line 11. Leave the parenthesis (that is, the () ) empty, and jQuery will return the text that’s already in the object.

Several jQuery functions are like this. We’ll see more of them later.

Testing stuff

Line 12 introduces the if statement. The if statement lets browsers make decisions, doing different things depending on the circumstances.

The if statement only has two possibilities. It does one thing, or the other, and that’s it. Other statements let you have more than two options, but that’s for a future lesson.

The if statement looks like this:

if ( test ) {
  stuff to do if test is true
}
else {
  stuff to do if test is false
}

Figure 11. Iffy if, the ifster

The test is usually a comparison of some sort. The == in line 12 means “is equal to.” It’s true when the things on either side of the == are the same. Otherwise, it’s false.

Don’t confuse = and ==. They’re different. = means “put the thing on the right into the variable on the left.” == means “compare the things on the right and left.”

Back to the example.

var button_caption = $("#show_hide_puppy").text();
if ( button_caption == "Show puppy") {
  $("#show_hide_puppy").text("Hide puppy");
}
else {
  $("#show_hide_puppy").text("Show puppy");
}

(Part of) Figure 10 (again). Toggling the button’s caption

So line 12 says,

Is the variable button_caption equal to Show puppy?

If it is, the browser runs line 13, setting the button’s text to Hide puppy. If it isn’t, the browser runs line 16, setting the button’s text to Show puppy.

Exercise: Caption update

You wrote a page to show and hide your drawing. Update it so that it changes the button’s caption appropriately.

Upload your file to the server. Put the URL below.

(Log in to enter your solution to this exercise.)

Now try this one.

Exercise: Two photos

Find two photos of animals. Create a Web page with two buttons and the two photos. One button shows and hides one of the images. The other button shows and hides the other.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Summary

In this lesson, you learned how to show and hide an image in response to an event. You saw your first example of the an if statement.

What now?

With just what you know now, you can make a slide show page. Let’s do it.

Project: Making a slideshow

Where are we?

You learned how to show and hide an image. You saw the if statement in action. Now let’s make a simple slide show.

This page’s goals

By the end of this page, you should:

  • Know how to control a sequence of events.
  • Know how to restart an event sequence when it gets to the end.

Slide show behavior

Let’s make sure we know what we want from the slide show.

Please try the page. Click on the arrow a few times. Notice that there are four photos. The show cycles back to the first one when it’s done.

The page is showing one image, cycling it as the user clicks.

Image cycle

Figure 1. Image cycle

We’ll actually use only one <img> tag. By changing its src attribute, we’ll change which photo the <img> tag is showing.

Suppose we gave each photo a number. This is what would be happening.

Numbered image cycle

Figure 2. Numbered image cycle

The slide number starts at 1. On each click, it goes up by one. When it gets to 4, a click sends it back to one. Each event is a step in the cycle. Click – 1 – click – 2 – click – 3 – click – 4 – click – 1 – click – 2 – ...

Let’s move closer to the actual code. Suppose we name the image files slide1.jpg, slide2.jpg, slide3.jpg, and slide4.jpg. The name of the image for the current slide would be:

slide + the slide number + .jpg

If we could put that into the src attribute of the <img> tag, it would show the current slide.

Closer to code

Figure 3. Closer to code

Here’s some pseudocode for the click() event:

Increase the slide number by one.
The new slide name is slide + slide number + .jpg.
Set the <img> tag's src to the slide name.

Wait a minute. I forgot something. There is no slide 5. Hmm. How about this?

Increase the slide number by one.
If the slide number is more than 4, make it 1.
The new slide name is slide + slide number + .jpg.
Set the <img> tag's src to the slide name.

That’s better.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Slide Show</title>
    <style type="text/css">
      #forward {
        cursor: pointer;
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p><img id="forward" src="forward_arrow.gif" alt="Forward"></p>
  </body>
</html>

Figure 4. The code!

Let’s look at the HTML first. Line 28 is the <img> that shows a photo. Notice that the <img> tag has id and alt attributes. The id will let us mess with the image in JavaScript. The alt is needed for the page to validate.

But there’s no src attribute in line 28. That’s because the src in set in JavaScript. Its value changes with each click.

Line 29 is the thing that users’ click on. I found the image in a clip art library I bought. The <img> tag in line 29 also has an id, because I want to attach an event to it.

The CSS for this image is in lines 7 to 9. #forward means “Find the thing with an id of forward.” The style sets the mouse cursor to the pointer, which by default looks like a hand.

Now for the JavaScript. Line 14 creates the variable slide_number, and sets its initial value to 1. This variable will go up by one every time the user clicks on the arrow.

Line 15 is:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

$("#slide") says “Find everything with an id of slide.” There is only one thing with that id. Again, don’t forget the #.

"slide" + slide_number + ".jpg" computes the name of the file to show in the <img>. If slide_number is 1, then this works out to slide1.jpg. If If slide_number is 4, then this works out to slide4.jpg.

The attr() function sets an attribute of a tag. There are lots of different attributes, so you need to tell attr() which one to set. Then you give it the value.

In English, this:

$("#slide").attr("src", "slide" + slide_number + ".jpg");

says:

Find the thing with an id of slide. Set its src attribute to the value "slide" + slide_number + ".jpg".

Line 16 binds code to the click() event of the forward arrow. So the code from lines 17 to 21 is run whenever the user clicks on the arrow.

Line 17 adds one to the variable slide_number. That’s what ++ does – add one to a variable. You could also write:

slide_number = slide_number + 1;

That says “Take the value of the variable slide_number, add 1 to it, and put the result into the variable slide_number.” It’s common for variables to overwrite their own values like this.

What happens when the user gets to the last slide (slide 4), and clicks on the forward image? There are no more slides! So, back to slide 1. Here’s the if statement:

if ( slide_number > 4 ) {
  slide_number = 1;
}

When slide_number > 4 is true, run the code in the braces. This sets slide_number back to 1.

Finally, line 21 changes the src attribute of the <img> tag, to show the right slide. It’s the same code as line 15.

W00f!

Tracking program execution

I’ll change the JS to this:

$(document).ready(function() {
var slide_number = 1;
$("#slide").attr("src", "slide" + slide_number + ".jpg");
$("#forward").click(function() {
  slide_number ++;
  alert("slide_number before if: " + slide_number);
  if ( slide_number > 4 ) {
    slide_number = 1;
  }
  alert("slide_number after if: " + slide_number);
  $("#slide").attr("src", "slide" + slide_number + ".jpg");
  alert("Slide file name: " + "slide" + slide_number + ".jpg")
});

Figure 5. alert()

Please try it. Notice how The alert() statements show how the program is working.

This is especially handy if there’s a bug in the program. It helps you understand what the program is doing. You can compare what you see to what you expect to see. For example, if you expect slide_number to change from 5 to 1, and it doesn’t, that’s a clue that there might be something wrong with the if.

Exercise: A slideshow

Create your own slide show of at least eight images.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Enhance the slide show

Let’s make some improvements.

Show the slide number

First, let’s show the slide number. Try my solution.

I added this to the HTML, creating a place to show the slide number:

<p>Slide number <span id="slide_number"></span>.</p>

Recall that <span> creates a spot on the page you can refer to with its id.

The I added this to the JavaScript:

$("#slide_number").text(slide_number);

I added it twice, after lines 15 and 21 of Figure 4.

Add a back button

Next I added a button to go backward in the slide show. You can try the page.

Here’s the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Slide Show</title>
    <style type="text/css">
      #forward, #backward {
        cursor: pointer;
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        var slide_number = 1;
        $("#slide").attr("src", "slide" + slide_number + ".jpg");
        $("#slide_number").text(slide_number);
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
        $("#backward").click(function() {
          slide_number --;
          if ( slide_number < 1 ) {
            slide_number = 4;
          }
          $("#slide").attr("src", "slide" + slide_number + ".jpg");
          $("#slide_number").text(slide_number);
        });
      });
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p>Slide number <span id="slide_number"></span>.</p>
    <p>
      <img id="backward" src="backward_arrow.gif" alt="Backward">
      <img id="forward" src="forward_arrow.gif" alt="Forward">
    </p>
  </body>
</html>

Figure 6. Going backward

Look at line 7. This tells the browser to apply the same CSS rule to two different things. Don’t forget the ,.

Line 26 shows the — operator. It subtracts 1 from a variable.

Lines 27 and 28 make sure that slide_number does not go below 1.

Exercise: Improve your slideshow

Improve the slide show you made. Add:

  • Slide number.
  • Back button.
  • Home button. It always takes you back to the first slide.

Add JavaScript alert() statements so that you can see how the program works.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Making a function

Web sites are always changing. Webers know this, and design sites so they’re easy (and therefore cheap) to change. A WEb site is maintainable if it’s easy to change.

One easy way to improve maintainability is to reduce duplicate code. In Figure 6, lines 15 and 16 are the same, lines 22 and 23 are the same, and lines 30 and 31 are the same. That’s because the program is changing the photo three times: once during initialization, once on page forward, and once on page back.

What if we need to change what the photo display code does? Maybe we want to add, say, a description to each photo (which we’ll do soon). We’d have to change the code in three places. The chances for error go up, and the longer it’s going to take to make everything work.

I’m going to put the repeated code into its own function. A function is a piece of code with a name. We’ve already used functions, like toggle() and text(). Those functions are part of jQuery. But we can make our own as well.

Here’s the new JavaScript.

$(document).ready(function() {
var slide_number = 1;
show_slide(slide_number);
$("#forward").click(function() {
  slide_number ++;
  if ( slide_number > 4 ) {
    slide_number = 1;
  }
  show_slide(slide_number);
});
$("#backward").click(function() {
  slide_number --;
  if ( slide_number < 1 ) {
    slide_number = 4;
  }
  show_slide(slide_number);
});
});

//Show the slide with the number given.
function show_slide(slide) {
  $("#slide").attr("src", "slide" + slide + ".jpg");
  $("#slide_number").text(slide);
}

Figure 7. Adding a function

The function in lines 33 to 36 is called show_slide(). It takes one parameter, the number of the slide to show. A parameter is a value that goes into the function. The function uses the parameter to do its work.

The function is called on lines 15, 21, and 28. Note that there is no relationship between the name of the parameter in the function (slide) and the name of the variable that is passed in (slide_number). I could change slide to hippos_are_very_large in show_slide(). As long as I changed it in the entire function, it would still work.

If I want to change how slides are shown everywhere in the program, I make the change in one place: show_slide(). The function calls – lines 15, 21, and 28 – don’t say how to show a slide. They just say, “Show it!” The function does the work.

You can try the page. It will act exactly the same as the previous version. Users won’t notice any difference.

But when it comes time to change the page, you’ll be able to do it faster and more accurately.

Adding image descriptions

Let’s add a description to each image, so that the user knows what s/he is looking at. Please try the page.

Here’s the page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Slide Show</title>
    <style type="text/css">
      #forward, #backward {
        cursor: pointer;
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        var slide_number = 1;
        show_slide(slide_number);
        $("#forward").click(function() {
          slide_number ++;
          if ( slide_number > 4 ) {
            slide_number = 1;
          }
          show_slide(slide_number);
        });
        $("#backward").click(function() {
          slide_number --;
          if ( slide_number < 1 ) {
            slide_number = 4;
          }
          show_slide(slide_number);
        });
      });
      
      //Show the slide with the number given.
      function show_slide(slide) {
        $("#slide").attr("src", "slide" + slide + ".jpg");
        $("#slide_number").text(slide);
        if ( slide == 1 ) {
          $("#description").text("Renata as a puppy, chewing on a human's feet.");
        } else if ( slide == 2 ) {
          $("#description").text("Renata wondering what is going on.");
        } else if ( slide == 3 ) {
          $("#description").text("Renata loves to chase balls.");
        } else if ( slide == 4 ) {
          $("#description").text("What's that? Can I eat it?");
        }
      }
    </script>
  </head>
  <body>
    <h1>Slide Show</h1>
    <p><img id="slide" alt="Slide show image"></p>
    <p>
      Slide number <span id="slide_number"></span>.
      <span id="description"></span>
    </p>
    <p>
      <img id="backward" src="backward_arrow.gif" alt="Backward">
      <img id="forward" src="forward_arrow.gif" alt="Forward">
    </p>
  </body>
</html>

Figure 8. Showing a description

Line 53 is where the description goes. The <span> is an inline tag, so the browser shows the description as part of the same paragraph as the slide number. You can read about the difference between inline and block tags.

Lines 36 to 44 show a different use of the if statement. Do this, or that, or that, depending on the value of slide.

Because I used a function, I only had to add the description code in one place. If I hadn’t used the function, I would have had to add the code in three places.

Let’s w00f for functions! W00f! W00f! W00fy w00f w00f!

Going deeper

Summary

On this page, you learned how to control a sequence using events, with a variable keeping track of where the page is in the sequence.

You also learned about functions. They make your Web pages more maintainable.

What now?

Now it’s time to do some more exercises. Yay! Remember to ask your study group for help if you need it.

Exercises: A Web page with images

Exercise: Three dogs

Here are some images. Right-click and save to download them to your computer.

Kieran

CC

Renata

Background

Use them to create a page that looks like this. Don’t look at the source until you’ve tried it yourself!

Hints:

  • Here’s some HTML: <p><img id="kieran" src="kieran.jpg" alt="Kieran"></p>
  • You can use # in CSS to select an item with a given id.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Exercise: The best animal

Download these three images:

Cat

Dog

Horse

Write a page that acts like this one. Don’t look at the source until you’ve tried it yourself! When the user clicks on the dog, one message appears. When the user clicks on another animal, a different message appears.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Exercise: Money counter

Download these images to your computer:

One dollar bill

Two dollar bill

Five dollar bill

Ten dollar bill

Write a page that shows the images. When the user clicks on an image, the page updates a total by the appropriate amount. You can run my solution to see how it works, but don’t look at the source code until you’re tried it yourself!

Hint: I used pseudocode like this:

When someone clicks on a bill:
Get the current total from the page.
Add the bill's value to the total.
Show the new total on the page.

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Exercise: Image quiz

Write three HTML pages that make an animal quiz. Each page shows four images, and asks the user to click on a particular animal.

You can download all of the images in a zip file. The images are sized, and ready to use. Start by downloading the images, and extracting them into a directory.

Here’s the first page, scaled down to fit in this space:

First page

Figure 1. First page

The text says “Click on the dog.”

When the user hovers over an image, the cursor should be a hand:

Hover cursor

Figure 2. Hover cursor

If the user clicks the wrong image, show this:

Wrong

Figure 3. Wrong

The sad face is included in the image zip file.

If the user clicks the right image, show this:

Right

Figure 4. Right

If the user gets it right, the “You got it wrong” message should vanish before the “You got it right” message appears.

The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

The “You got it right” feedback includes a link to the second page. Here it is.

Second page

Figure 5. Second page

The text says “Click on the goose.” The page works the same as the first one.

Here’s the third and last page:

Third page

Figure 6. Third page

The message says “Click on the echinda.”

Here is the “right” feedback for the third page:

Third page

Figure 7. Third page feedback

Hints:

  • Keep all the files together in one directory.
  • Use an external style sheet, linked to all three HTML files.
  • Use a <div> tag to group the tags in a feedback area. E.g.:

<div id="right">
   <img src="lego
   You got it!<br>
   ...
</div>

  • Add a click() event to each image.

You can try my solution, but do it yourself first!

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Exercise: A dog slideshow

Make a slideshow of dog photos with captions. Your show should be at least four slides long.

  • Find some dog images that you can legally use.
  • Add funny captions to them with a graphics program.
  • Make a slideshow page with forward and back arrows that work. Find images you can legally use.
  • Show a text caption below each image, as well as the one on the image itself.
  • Use seamless tiles for the page background.
  • Add a header to the page. Use seamless tiles for the header area as well.
  • Add borders around the header and photo.

Here is a page sample. Use different images and captions for your solution:

Sample

Figure 1. Sample

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)