A page with images

Images are very important on the Web. They help explain things.

Pixels
Like what pixels are.

Images also help set a mood.

Puppy
How cute is this?

The Web wouldn’t be the Web without images.

You need to know how to use images. Not only how to insert them in HTML. But also where to get images, how to change them, and, most important, what they’re for.

That’s what this lesson is about.

You’ll also learn how to manipulate images with jQuery. This is Much Fun. You’ll show images, hide them, resize them, all with animated effects.

Finally, you’ll learn more about 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:

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 an interface 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.

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 look at that and not 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.

Most images on the Web are simple. You can make almost all the images in an entire site with just a few basic skills.

Summary

On this page, you learned:

  • What an informational image is.
  • What an interface image is.
  • What a structural image is.
  • The attributes of good images.
  • What basic image skills you need for Web work.

What now?

Let’s start by exploring how computers show images.

How computers show images

Where are we?

You know that it’s important to have basic image skills.

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

This lesson’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 lesson is about.

This lesson’s goals

By the end of this lesson, 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 differentiate. Here are two objects:

Two colors

Figure 1. Two colors

They are different colors. One is (255, 159, 99). The other is (255, 159, 100). So one has slightly more blue. I can’t tell the difference. Can you?

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 image, 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. 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. Compare these two images.

Normal image
4.0K

Compressed too much
0.7K

Figure 2. Compressed too much

The good news is that the second file is tiny, even though the image itself ls larger. Too bad it’s junk.

JPEG is best for photos, which 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.

256 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 3. 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 4. 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 5. Transparent GIF

The PNG format

The portable network graphics (PNG) format was designed to replace GIF. PNG is lossless since it 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. That’s what GIF does. The cow in Figure 5 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 6. PNG flamingo

Here’s a blue spot:

Blue spot

Figure 7. 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 8. 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 9. Searchlight

I wrote some JavaScript to move the searchlight over the text. The pixels in the searchlight have some translucency, so the text underneath always shows through.

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 everything else. There are lots 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 HTML code into your page to embed the movie in your site. YouTube gives you the code, so you can just copy-and-paste.

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.

Apple doesn’t support Flash on iPhones or iPads. These are popular devices. Some people think Flash is on the way out. Time will tell.

Summary

In this lesson, 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, interface, 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 lesson’s goals

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

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

Using other people’s images

There are millions of images you can use freely on your Web sites. But before you use an image, make sure you understand its license. A license is a legal document telling you what you can do with the image.

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.

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 people 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 lesson. 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.

Photos

You can get photos from many places. Here are a few.

BurningWell

BurningWell is a collection of public domain photos. The collection is not as large as some others, 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 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.

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.

Put the URLs of the images below. To find the URL of an image, right-click on it in Firefox, and select "View image info." The command may be different in other browsers.

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

Can't find the 'comment' module! Was it selected?

Interface and structural

These are images for buttons, dividers, and so on. Look for images that come in sets, that is, a collection of buttons, dividers, and other elements that have the same look.

Open Source Web Design

Many complete site layouts, including image sets. The CoreDogs theme started with an OSWD design.

FullMoon Graphics

Some creative image sets.

Chibi Creations

Neat stuff, if you like chibies.

Google Directory

List of Web sets. Lots o’ stuff here.

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

Draw and scan

Robot dog
By zombiecatfire13

Zombiecatfire13 drew the robot dog, and said I could add it to CoreDogs. I scanned it in.

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, if you want. 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 lesson’s goals

By the end of this lesson, 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.

Paint.NET is a popular image editor for Windows. It’s free, and easy to use. It can handle common Web image tasks, cropping, resizing, recoloring, fixing artifacts in photos.

For the Mac, iPhoto can do some basic tasks. You can see a list of low-cost Mac image editors.

GIMP is another popular tool. It’s free, and runs on all the major operating systems. It’s more powerful than Paint.NET, but harder to use and harder to learn. I use GIMP for much of my image work.

We’ll use Paint.NET in CoreDogs. If you run Windows, you should download and install it.

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

Cropping a photo

Often you want to use just part of 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.

Open the file in Paint.NET. Use the select tool. Choose part of the photo.

Selecting

Figure 2. Selecting

Now use the crop command.

Cropping

Figure 3. Cropping

You end up with a cropped image. W00f!

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.

Maintain aspect ratio

Figure 7. Maintain aspect ratio

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 8. 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 9. 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.

I add the text into the new layer.

Adding text

Figure 10. Adding text

I got:

Meat taste

Figure 11. Meat taste

Since the text is in a separate layer, I still have the original image underneath. If I change my mind about what the text should say, I just change the text layer. I can delete the text layer, add a layer with other images, and so on.

Layers are important. Choose an image editor that has them.

To make the text look a little better, I added a slight raised effect. To do it, I added another layer underneath the text layer:

Shadow layer

Figure 12. Shadow layer

I copied the text layer, changed its color, moved it a little, and blurred it a little. Paint.NET stacks the layers on top of each other. This was the result:

Meat taste, raised text

Figure 13. 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 need a dog photo, try morgueFile.com.

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

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

Can't find the 'comment' module! Was it selected?

Drawing tools

So far, we’ve worked on photos and other pixel-based images. With these tools, you usually work with individual pixels:

Drawing tools are different. They make it easy to create drawings like this:

Ajax drawing

Figure 14. Drawing

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

Each element is a separate object. You can change each one separately. For example, I can grab one of the objects in Figure 14:

Selected a line

Figure 15. Selected a line

Then I can mess with that object, leaving everything else alone:

Changed object

Figure 16. Changed object

Moving all the pixels around to make the new line would be a pain. But I don’t have to. The drawing program makes it easy for me to reshape a line.

Drawing programs store images in many different formats. Web browsers can’t show most of them. So, when you have the drawing right, you make a bitmap copy, in a JPEG, GIF, or PNG. This is sometimes called “exporting” the image. I often use a screen capture program for this step, as we’ll see later.

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 17. Dog happiness

It’s a combination of a pixel object (the dog) and drawing objects (everything else). That’s common in Web work. You use pixel tools for photos and such, and drawing tools for lines and things.

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

Here’s the original drawing:

Original drawing

Figure 18. Original drawing

It’s a pixel object – a bunch o’ colored dots.

There are some artifacts around the dog. Artifacts are errors, like extra pixels or changes in pixel colors.

Artifacts

Figure 19. Artifacts

They usually result from problems when scanning an image from a book into a computer, or converting from one image format to another.

This is pixel work, so I used Paint.NET for this part of the task. The eraser tool can remove extra pixels around the head.

Removing artifacts

Figure 20. Removing artifacts

I zoomed in so I could work more easily. I set the radius of the erase to 5 pixels.

Once the artifacts were gone, I told Paint.NET to save the dog head as a PNG.

Then I started Draw, with a blank page. I told Draw to insert the dog head.

Next, I added some text:

Adding text

Figure 21. Adding text

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

Then I added a connector:

Adding a connector

Figure 22. Adding a connector

A connector is a line that connects two other objects. Notice the anchor points: the 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 use 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.

Figure 23. Moving the text

Choose a drawing 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 17 (again). Dog happiness

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

When you choose a drawing tool, look for a tool that includes geometric objects.

Finally, I added a gradient to the heart:

Adding a gradient

Figure 24. Adding a gradient

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

Now I’ve finished the drawing. W00f! Time to get it on a Web site.

Remember, there’s a problem. Browsers show images in JPEG, GIF, and PNG formats (and maybe others, but these are the Big Three that work in all modern browsers). But my drawing file is not in one of those formats. It has the extension .odg, used by OpenOffice Draw. Browsers don’t know how to show .odg files.

How do I get my drawing in one of the Big Three formats? There are various ways. I chose to do something simple…

Screen capture

This means saving a piece of your computer screen into a file. Often called a screen shot. A screen shot is a bitmap image, with the pixels that were on your screen.

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.

I use SnagIt for CoreDogs. It costs money, but is worth it if you do lots of screen captures.

Summary

On this page, you learned about image editors, image viewers, drawing programs, and screen capture programs. You learned how to do some basic tasks, like crop and resize images.

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 lesson’s goals

By the end of this lesson, 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

Line 10 shows the <img> tag at work:

<img src="food_love_happiness.png">

Give the <img> tag the name of the file to show, in the src attribute. You can see this page in your browser.

Notice that your browser needs two files to show this page:

  1. The HTML file, with an extension .html.
  2. The image file, with an extension .png.

So image data are not stored in HTML files. Image data are stored in separate files. HTML files are always just plain text.

For now, we’ll keep all of our files in the same directory on the hard disk. So the directory for the page in Figure 1 might look like this:

Directory with HTML and image files

Figure 2. Directory with HTML and image files

When you upload the files to your server, upload both files, and keep them together.

It’s not always good practice to keep the files together. But we’ll deal with that later.

The alt attribute

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

So the <img> tag about should really be something like:

<img src="food_love_happiness.png" alt="Food, exercise, and love = a happy dog">

There are two reasons you should use the alt tag.

First, 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.

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.

There’s a second reason you should use the alt tag: it helps search engines know what the image is about. People are more likely to find your page if you add alt attributes to your images.

Exercise: Show a drawing

Here a drawing of someone geeking out:

Geek

Download the image to your computer. Create an HTML page that shows the image. Use a relative URL for the image file.

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

Can't find the 'comment' module! Was it selected?

Summary

  • Use the <img> tag to show images.
  • 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 a 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.

Boxes

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. Each <p> is in a box, a rectangle of space on the screen.

The text you’re reading now is in a box. You could draw a rectangle around the text, with “The” in the upper left, and “right.” in the lower right.

Browsers create boxes for <p>, <h1>, <h2>, <ul>, <ol>, and other tags. Including the <img> tag. Each one creates a box (a rectangular space) on the screen.

You control the box by using the CSS attributes border, margin, and padding.

Let’s start with 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">

I created a class in the CSS (don’t forget the .), and set the border-style. I used the class in the HTML with the class attribute of the <img> tag.

Here’s a dashed border:

Dashed border

Here’s the code:

.solid_border {
  border-style: dashed;
}

The default border style is hidden, meaning no border.

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

There are four borders around the image: top, right, bottom, and left. border-style sets all four to be the same. You can give each one 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, right, bottom, left. 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. I put all the options in a single border style:

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

Margins and padding

We’re talking about boxes around elements. 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

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 7. Dog matrix with margin and padding

The box model

Put border, margin, and padding together, and you have the box model.

The box model

Figure 8. The box model

The box model shows how border, margin, and padding combine. And the box model isn’t just for images.

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

Here’s a buttony thing made with the box model.

Box model example

Figure 10. Box model example

Thick gray borders on the bottom and right create a shadow. The thinner lines on the top and left add to the button effect. The color for the top and left is a slightly darker version of the background color.

Summary

Browsers use the box model to create rectangular areas on the screen. You can change the way the boxes look with border, margin, and padding.

What now?

You can make text wrap around an image. Let’s see how.

Floating images

Where are we?

You learned how to put an image on a page. You know how to put a border around it, with margins and padding. Time for more image fun.

This lesson’s goals

By the end of this lesson, you should know how to move an image to the left or right of a page, and have text wrap around it.

The goal

You’ve seen pages like this:

Renata

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Figure 1. Image floated left

The image is on the left of the page, and text wraps around it. There’s a small gap between the image and the text.

The image could be on the right:

Renata

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah blah blah. Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Blah blah blahity blah blah. Blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blah blah blahity blah blah. Blah blah blahity blah blah.

Figure 2. Image floated right

Let’s see how you do that.

Basic floating

Check out this code:

.left {
  float: left;
}
...
<p>
  <img src="renata.png" alt="Renata" class="left">
  Once upon a time, there was a dog named Renata. Renata
  was a happy hound. She liked to play, digging holes, 
  pulling ropes and chasing balls.
</p>

Figure 3. Floating left

There’s a paragraph from lines 5 to 10. The first thing inside the <p> is an <img> (line 6). It’s given a class of left. left is defined in the CSS, on lines 1 to 3.

float:left is applied to the image. Here’s what it looks like:

Floating left - result

Figure 4. Floating left – result

You can look at the page.

That’s all there is to it. The float property moved the image to the left.

Suppose I change the code to this:

.right {
  float: right;
}
...
<p>
  <img src="renata.png" alt="Renata" class="right">
  Once upon a time, there was a dog named Renata. Renata
  was a happy hound. She liked to play, digging holes, 
  pulling ropes and chasing balls.
</p>

Figure 5. Floating right

Line 2 says right instead of left. It looks like this:

Floating right - result

Figure 6. Floating right – result

You can try it.

Renata
Renata

Look at the code. You named the class left in Figure 3, and right in Figure 5. Did you have to do that?

Kieran
Kieran

No, I could have named the class anything. This would work the same:

.llama {
   float: left;
}
...
<img ... class="llama">

Or this:

.leaping_lemons {
   float: left;
}
...
<img ... class="leaping_lemons">

I named the classes left and right to describe what they do. It makes it easier to understand the HTML.

Adding whitespace

Here’s the image floated left:

Floating left - result

Figure 4 (again). Floating left – result

The text is right up against the image. It doesn’t look very good.

I can use the box model you just learned about to fix that. Suppose I changed the class to:

.left {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
}

Figure 7. Making a gap

I’ve added a 10 pixel margin to the right of the image, and to the bottom of the image. Here’s what it looks like:

Making a gap - result

Figure 8. Making a gap – result

You can try the page.

Adding a border

As well as margin, the padding and border properties work on a floated image. Use them to make borders. Let’s say I wanted this:

With a border

Figure 9. With a border – result

There’s a small gap between the image and the border, then another gap between the border and the text.

Here’s the class:

.left {
  float: left;
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 3px;
  border: 1px black solid;
}

Figure 10. With a border

You can try it.

The padding (line 5) adds the gap between the image and the border. The margin (lines 3 and 4) adds the gap between the border and the text.

Renata
Renata

A question.

Look at the gap between the bottom of the border and the text in Figure 10:

Vertical gap

Why is it so large?

Kieran
Kieran

The margin below the border drops just a little into the line of text starting with “the.” The browser won’t draw part of a line of text, so it drops down to the next line, leaving that big gap.

It’s hard to control this vertical gap precisely. It depends on the size of the font, whether the user has zoomed in, and other things.

Exercise: The dog party

Project Gutenberg is a collection of literary works that are not under copyright in the United States. Take a story from the collection, and float some illustrations left and right.

I used The Dogs’ Dinner Party, by an unknown author. Have a look at the original. You can use another story, if you want.

The story includes text and images. I only used a small part of the story. You can use more if you want. I shrank the images to this:

Writing invitations
Receiving an invitation

Figure 1. Smaller images

Float your images to the left and right, with a gap between images and text. Here is part of what I made:

Result

Figure 2. Result

Create your own story page, with the look you want. Make sure you float some images to the left, and others to the right.

Upload your work to your server. Enter the URL.

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

Can't find the 'comment' module! Was it selected?

Summary

  • You can float images left and right with the float property. Text wraps around the image.
  • Use the margin property to put space between the text and the image.
  • Use the border property to add a border to the image. Use padding to add space between the image and the border.

What now?

Let’s add captions to image.

Images and captions

Where are we?

You know how to put images on a page. And you know about the box model. Now let’s put them together, so captions float around with their images.

This lesson’s goals

You’ll learn that:

  • Captions can be above or below images.
  • An image and a caption can be wrapped in a <div>, making a single block.
  • An image-caption block can be floated left and right.
  • You can add borders to image-caption blocks.

Caption options (say that five times fast)

Some images on Web sites have captions. Here’s an example:

Bulldog

Bulldog

There’s an <img> tag and some text. But we want them to stay together. That’s what this lesson is about.

Let’s talk about some formatting options:

  • Caption position
  • Image block position
  • Borders.

Caption position

This one’s easy. Is the caption above or below the image?

Like this:

Bulldog

Bulldog

Or like this:

Bulldog

Bulldog

Here’s the code for the latter:

<p><img src="bulldog.jpg" alt="Bulldog"></p>
<p>Bulldog</p>

Image block position

Wrap the image and caption in a block, and you can position them in the page. For example, this image and caption are kept together on the left of the page:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

The image and caption float together, as a single unit.

Here’s the code.

.image_caption_left {
  float:left;
  text-align:center;
  margin-right:10px;
}
...
<div class="image_caption_left">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
Bulldog
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

A <div> wraps the image and caption (lines 7 to 10). It keeps the image and caption together. When we move the <div> around, we move the image and caption as a single unit.

float: left; (line 2) positions the block to the left of the content. margin-right:10px; (line 4) leaves a small gap between the block and the blah blah blah.

Now let’s look inside the block. A <br> (end of line 8) puts the image and caption on different lines. text-align:center; (line 3) centers the image and caption within the block. text-align applies to the contents of the block, not the block itself.

Changing line 9 to this:

<em>Bulldog</em>

makes it easier for the user to see that the caption is not part of the regular text. Here’s what it looks like:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Of course, you can float to the right as well:

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Here’s the code.

.image_caption_right {
  float:right;
  text-align:center;
  margin-left:10px;
}
...
<div class="image_caption_right">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
Bulldog
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

The easiest thing of all is to center the image:

Bulldog

Bulldog

Here’s the code.

.center {
  text-align:center;
}
...
<p class="center"><img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"></p>
<p class="center"><em>Bulldog</em>

Borders

Let’s add a border to the image-caption block.

Bulldog
Bulldog

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah! Blah blah blahity blah. Blahity blah blah. Blah!

Here’s the code.

.image_caption_left {
  float:left;
  text-align:center;
  margin-right:10px;
  padding:5px;
  border:1px black dotted;
}
...
<div class="image_caption_left">
<img src="/content_media/lessons/clientcore/web_page_with_images/bulldog.jpg" alt="Bulldog"><br>
<em>Bulldog</em>
</div>

<p>Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! 
Blah blah blahity blah. Blahity blah blah. Blah! </p>

Lines 5 and 6 are new. Line 5:

padding:5px;

adds whitespace between the image and caption, and the border. Line 6:

border:1px black dotted;

adds the border. Of course, you can change the thickness, color, and style of the border.

Summary

  • Captions can be above or below images.
  • An image and a caption can be wrapped in a <div>, making a single block.
  • An image-caption block can be floated left and right.
  • You can add borders to image-caption blocks.

What now?

A cool thing you can do with Web pages is to add background images. Let’s take a look.

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 lesson’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 lesson, you should:

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

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, from the Zen Garden. 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 1. 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 2. Using the tile

Figure 2 is not a screen shot. It’s made by some HTML and CSS I typed into this page. Here’s roughly what I did to create Figure 2.

...
.tiled {
  font-size: 20px;
  color: white;
  padding: 20px;
  background-image: url('tile.gif');
}
...
<div class="tiled">
  <p>Hi there!</p>
  <p>This is a tiled background. 
  Notice how the edges of the tile are seamless?</p>
  <p>There are a bazillion seamless tiles you can use
  for free, or you can make your own.</p>
  <p>We now return you to your regular background.</p>
</div>

Figure 3. Making Figure 2

There are two new things here.

<div>

There’s a new tag: <div>. <div> groups other tags together. Then, what you do to the <div> affects the entire group.

<div> is used to make a container on the page. Have another look at Figure 2. Figure 2 is a chunk of this page that I wanted to be different from the rest. With a different font, and with a background.

But how do I tell the browser that I just want to treat that one part of the page differently? That’s what <div> is for. It makes a container. By styling the container, I style everything in it.

In fact, most HTML tags create containers. Consider this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Container Samples</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      .dog {
        /* Pale blue */
        background-color: #99FFF9;
        font-size: 22px;
      }
      .cat {
        /* Pale green */
        background-color: #B3FF84;
        font-size: 11px;
      }
    </style>
  </head>
  <body>
    <p class="dog">
      I am the <strong>first</strong> container.<br>
      Yes. I am.
    </p>
    <p>I'm a container, too. I am the second container.</p>
    <p class="cat">
      I think I am the third container.
    </p>
  </body>
</html>

Figure 4. <p>s are containers

You can try it. This is what you’ll see:

Rendered containers

Figure 5. Rendered containers

I wanted every character in the text “I am the first container” to be in a large font. The easiest way to do it? Look for a container that holds the text. There was one already there – the <p> starting on line 20. So I gave it a class, and made a rule for the class in the CSS.

Use <div> when there isn’t already a container for the content you want to mess with. <div> by itself doesn’t actually show anything on the screen. It’s just for creating containers.

background-image

Here’s Figure 3 again:

...
.tiled {
  font-size: 20px;
  color: white;
  padding: 20px;
  background-image: url('tile.gif');
}
...
<div class="tiled">
  <p>Hi there!</p>
  <p>This is a tiled background. 
  Notice how the edges of the tile are seamless?</p>
  <p>There are a bazillion seamless tiles you can use
  for free, or you can make your own.</p>
  <p>We now return you to your regular background.</p>
</div>

Figure 3 (again). Making Figure 2

The first new thing in it was the <div> tag. The second new thing is background-image:

background-image: url('tile.gif');

You tell the browser the name of the file you want to use as a background. Don’t forget the url(). For now, let’s put the tile file in the same directory as everything else, just to keep things simple.

By default, the browser repeats background images across and down the container, filling up the background:

Repeating tiles

Figure 6. Repeating tiles

That’s why the tiles have to be specially designed to fit together. Most images don’t work as tiles. Here’s a (resized) photo of my desk:

Desk

Figure 7. My desk

I cropped and resized part of it, and created the following:

Desk tile

Figure 8. Desk tile

Let’s try it.

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 9. Using the desk tile

Uh oh. Not so good. When it’s repeated, the edges don’t fit together.

The lesson: use images specially designed to be seamless tiles.

Some tiles are designed to be repeated in one direction, but not the other. Here’s another tile from GRSites.com:

Another tile

Figure 10. Another tile

The tile is wide, to stretch across a large container.

We want the image to tile like this:

Repeat vertically

Figure 11. Repeat vertically

We only want the tile to repeat vertically. We don’t want it to repeat horizontally, otherwise the red line on the left of the “paper” would appear more than once.

Check this out:

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 12. Using the tile

Here’s the CSS:

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

Figure 13. CSS rule for notepaper background

By default, browsers repeat background tiles in both directions. Line 6 overrides that. It tells the browser to repeat vertically only.

What happens when you don’t do it right? I’ve taken another paper background image from GRSites.com. Please have a look. I added a border so you can see the edges of the image.

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 14. Cropped tile

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 15. Using the cropped tile

Remember, the browser’s default action is to repeat background images in both directions. 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 16. 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 17. Using the cropped tile with background-repeat:repeat-y;

Ahhhh… Much better.

Using one large image

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

First, I created the image with the fade effect:

Background image

Figure 18. Background image

I won’t explain how I made the image, since it’s not a core concept. There’s an article if you’re interested.

Now that I have the image, I want to put it in the upper right of 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>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 19. Page with a background image

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 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;

Summary

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

What now?

Let’s talk a bit more about color. How do you select image colors, font colors, etc., that look good together?

eMe: Images

Where are we?

You know how to show images, how to create them, how to show them on a page, and how to style them (with the box model).

Let’s talk about your eMe. Remember, that’s the site you’ll use to promote your personal brand to employers and/or clients.

What is your brand?

You need to know what your eMe will say about you. We talked a little about this before.

If you’re like many people, you’re not sure about this. You might even be uncomfortable about calling yourself a “brand.”

Renata
Renata

I was thinking that.

Kieran
Kieran

What?

Renata
Renata

I’m not a…, well, a washing detergent.

Kieran
Kieran

Let me ask you this. What is a brand?

Renata
Renata

Ah, it’s…, um, a thing for advertising. Isn’t it?

Kieran
Kieran

Not really. It’s a set of beliefs that people attach to something.

Advertisers care about this. When you think “Google,” the Google people want certain beliefs to jump into your mind. Same with “Burger King” (yum!), “Apple,” and “Pontiac.”

Renata
Renata

I’m not like those things!

Kieran
Kieran

You are in one sense. When an employer or client thinks about you, you want certain beliefs to pop into their heads. Is that right?

Renata
Renata

No!

Kieran
Kieran

But beliefs will pop into their heads. People are just wired that way.

Kieran
Kieran

Well, I guess. That’s what I learned in Psych 101.

Kieran
Kieran

So it’s a question of what beliefs. How about “resentful,” “dull,” and “angry?”

Renata
Renata

I’m none of those things!

Kieran
Kieran

I know. But when someone doesn’t know you, beliefs can come from anywhere.

Use your eMe to say positive things about yourself. Things that are true. Simply point out the good things about you. That you are playful, for example.

That’s what personal branding is about. Pick some attributes of yourself that you want to highlight. Then create consistent messages about those attributes.

People in the business call it “personal branding.” You can call it something else if you like.

One thing. Never lie on an eMe. Never stretch the truth. Advertisers do it all the time. They encourage consumers to form inaccurate beliefs, without telling direct lies. Well, not usually.

This is where branding gets a bad name. But just because advertisers sometimes mislead, doesn’t mean that you should. You can create an eMe with honesty and integrity.

Feel any better about it?

Renata
Renata

Yes, I suppose. But promoting myself still feels kind of weird.

Kieran
Kieran

I get that. Many people are taught not to be too proud. But talk about yourself honestly, and you’ll be OK.

By the way, do you know how you want to promote yourself yet?

Renata
Renata

Not really.

Kieran
Kieran

Keep thinking about it.

Renata
Renata

OK.

Your brand will probably include things like “professional,” “easy to work with,” and “fun” (maybe in there, maybe not). You’ll need some photos of yourself. Here are some you should have.

  • You in professional dress. Dress collar (dogs), suit (humans). A tie if you’re a male human. I don’t understand ties. But humans seem to think they mean something. Odd.
  • You in business casual. Smart, colorful collar (dogs). Humans have different rules. Wearing just a collar is not enough for them. Do some Googling about business casual.
  • You with a team, if teaming is an aspect of your brand. Find some photos of yourself working with others.
  • You having fun. Running with the pack, chewing on a rope, chasing squirrels, whatever you’re into. Make sure the photos are attractive and make sense to someone not into your things. For example, don’t include a photo of you with a shredded squirrel corpse. Unless you want a hunting job.

Collecting your photos

Make a directory on your server. Upload photo files there. You might not use all of them immediately. But they’ll come in handy one day.

Colors and color schemes

Where are we?

You need to create the right look and feel for your Web site. You learned earlier that look and feel includes:

  • Page layout
  • Colors
  • Images
  • Typography
  • Effects

Let’s talk about color in this lesson. Both text and images have color. Text color is set with CSS. Image color is part of the images themselves. Choosing a set of colors that work well together is hard for, er, artistically challenged people like me.

This lesson’s goals

By the end of this lesson, 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

CSS rules set colors for text. Colors in CSS are usually represented as three numbers: the amount of red, green, and blue (RGB) 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;

“Hexadecimal” is just another way of writing numbers. 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 lesson

This lesson 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 people work with color, they want to say things like “make that blue brighter,” or “let’s try a paler orange.” That’s the way we’re used to talking about color.

It’s hard to do those things with RGB codes. Here’s an orange, and its RGB code:

Orange

Figure 2. Orange

How would you change the RGB code to make it paler? I’ll wait.

Oooo oooo ooooooo, ooo oooo ooo ooooooo oo,
Oooo oooo ooooooo, ooo ooo ooo ooo.

Figured it out? No? Don’t worry, I can’t figure it out either. People just can’t work with RGB codes. It’s too hard to figure out how much red, green, and blue to add (or subtract) to make a color paler.

RGB is precise, and it works for computers, but not for people. Is there something we can use instead of RGB, that’s also precise, and that people can use?

HSV works. It stands for Hue, Saturation, and Value. There’s a number for each one. So there are three numbers, just like RGB, but they mean different things.

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 3. 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 4. Primary hues

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

Mixing hues

Figure 5. 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 6. 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 7. 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 7, 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 8. 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 7. 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 7:

Value and hue constant

Figure 9. 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 7 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 10. 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 another person about color on a Web site? Have some charts like Figure 7 handy. Then you can say, “These are all reds, but different kinds of reds.”

More on this later.

Let me show why HSV is so handy. I wanted a buttony thing with a green background, and darker edges. This video shows how HSV and Paint.NET helped me do that.

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 3 (again). Color wheel

The wheel shows different hues.

You can make color schemes based on the color wheel. Let’s talk about 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 11. 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 12. Monochrome site

What a handsome fellow! Reminds me of someone.

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

Accent

Figure 13. Accent

If you need more than one accent color, consider making them tints and shades of the same hue. So if the accent is green, have a few different greens you can use as accents.

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

Blue monochrome

Figure 14. 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 14, you have to be more careful. Try using an accent hue that’s directly opposite on the color wheel:

Accent color for blue

Figure 15. Accent color for blue

This is exactly what’s happening in Figure 14.

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 16. 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 Figure 14 is based on actually looks like this:

Accent objects

Figure 17. Accent objects

The yellow-orange color of the accent objects is complementary (that is, opposite on the color wheel) 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 use it as one of the main colors of the site. Then you get a complementary color scheme.

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

Some reds and greens are complementary:

Red and green

Figure 18. Red and green

Here’s a site that uses them:

Complementary scheme in action

Figure 19. 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 20. 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.

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 employer might already have some standard colors. Look at the IBM site; 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.

DogOne tool is Whats its color. You can upload a photo, or enter the URL of one. Give it a try. Pick a photo, upload it, and see what colors are in it. Download the photo on the right if you don’t have one of your own handy.

If you have 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” suggest blues and greens in a analogous scheme. “Lively” and “fun” suggest something else.

Pick a few colors (including accent colors). Play with tints and shades. You won’t stay with them, 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.

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 21. 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 you figure out the colors being used. ColorZilla is an add-on for FireFox. When you install it, it adds an eyedropper to the Firefox status bar:

ColorZilla

Figure 22. 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 23. Starting the color analyzer

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

The color analyzer in action

Figure 24. The color analyzer in action

Exercise: Get a page's color scheme

Find a Web page you like. Use ColorZilla to get the colors on the page (you’ll need to install ColorZilla in Firefox).

Create a Web page like this one, showing some of the main colors on the page. Show maybe five or six colors, or however many are needed to show the main colors on the page.

I took a screen shot of part of the page. If you don’t have a screen capture tool on your Windows computer yet, try PicPick and Gadwin PrintScreen. Mac users will have to find something else.

You can look at the HTML of my solution to see how to write your own page.

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

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

Can't find the 'comment' module! Was it selected?

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?

Time to make a color scheme for your eMe 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 an 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 shown 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 a drawing

Here’s a drawing:

Yummie

Create an HTML page with a button that shows and hides the drawing.

Upload to your server. Put the URL below.

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

Can't find the 'comment' module! Was it selected?

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 to 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 a pretzel. 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.)

Can't find the 'comment' module! Was it selected?

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

Can't find the 'comment' module! Was it selected?

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 if statement.

What now?

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

eMe: 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 for your eMe.

What about? Pick something from your interesting stuff list.

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

Can't find the 'comment' module! Was it selected?

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

Can't find the 'comment' module! Was it selected?

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.

There are many ways to show the descriptions. I’ll use one of the easiest ways.

I’ll change the HTML so that it looks like this:

<body>
  <h1>Slide Show</h1>
  <p><img id="slide" alt="Slide show image"></p>
  <p>Slide number <span id="slide_number"></span>.</p>
  <p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
  <p id="description_2" class="description">Renata wondering what is going on.</p>
  <p id="description_3" class="description">Renata loves to chase balls.</p>
  <p id="description_4" class="description">What's that? Can I eat it?</p>
  <p>
    <img id="backward" src="backward_arrow.gif" alt="Backward">
    <img id="forward" src="forward_arrow.gif" alt="Forward">
  </p>
</body>

Figure 7. HTML for image descriptions

There’s an important difference in the way I’ve implemented the slides and the descriptions. There is one tag for all the slides. It’s the <img> tag on line 44. To show a slide, we change the contents of that one tag.

The way descriptions are handled in Figure 7 is different. There are four tags for the descriptions, a separate one for each description. They’re on lines 46 to 49. To show a description, we change which tag is showing.

So if we want to show the description of slide 1, we show the element with the id of description_1 (line 46), and hide the other descriptions. To show the description of slide 2, we show the element with the id of description_2 (line 47), and hide the other descriptions.

Renata
Renata

Wait a minute. The code is wrong.

Kieran
Kieran

Where’s that?

Renata
Renata

Look at line 46. It has an id and a class. Can you do that?

Kieran
Kieran

Sure. That’s part of how the code works. We’ll talk about that in a bit.

Let’s look again at what happens when a user clicks on the “Next slide” button. Just the logic of it, not the code, not just yet.

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.
Hide all of the descriptions.
Show the element (description_ + slide number).

As before, the first two lines work out which slide number the user wants to see. The next two lines show that slide. The last two lines show the description. The last line uses the slide number.

So the slide number is used for two things:

  • Select the photo to show, and
  • Select the description to show.

Here’s the new JavaScript.

<script type="text/javascript">
  $(document).ready(function() {
    var slide_number = 1;
    $("#slide").attr("src", "slide" + slide_number + ".jpg");
    $("#slide_number").text(slide_number);
    $(".description").hide();
    $("#description_" + slide_number).show();
    $("#forward").click(function() {
      slide_number ++;
      if ( slide_number > 4 ) {
        slide_number = 1;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
    $("#backward").click(function() {
      slide_number --;
      if ( slide_number < 1 ) {
        slide_number = 4;
      }
      $("#slide").attr("src", "slide" + slide_number + ".jpg");
      $("#slide_number").text(slide_number);
      $(".description").hide();
      $("#description_" + slide_number).show();
    });
  });
</script>

Figure 8. New JavaScript

Most of its the same as before. Let’s take a look.

When the page first loads, we want slide number 1 to be showing. That’s what lines 14 to 18 do. Line 14 creates a variable and sets it to 1. Line 15 shows that slide. Line 16 outputs the number of that slide.

Lines 17 and 18 are new. Here’s line 17:

$(".description").hide();

Remember that the . means class. So the line says.

Hide everything that has a class of description.

All four of the description elements have the class description. Here they are:

<p id="description_1" class="description">Renata as a puppy, chewing on a human's feet.</p>
bq. <p id="description_2" class="description">Renata wondering what is going on.</p>
bq. <p id="description_3" class="description">Renata loves to chase balls.</p>
bq. <p id="description_4" class="description">What's that? Can I eat it?</p>

So line 17 will hide all of the descriptions.

Once we’ve done that, we want to show just the description of the current slide. So line 18 is:

$("#description_" + slide_number).show();

Remember that # means id. So since slide_number is 1, this means:

Show the element with an id of description_1.

Renata
Renata

Oh, snap! That’s why each of the descriptions has an id and a class. The ids are all different. They have to be; you can’t reuse the same id on a page. The classes are all the same.

Kieran
Kieran

Right.

Renata
Renata

You use the class to refer to them all in one statement. Then you can hide everything at once.

Kieran
Kieran

Indeed.

Renata
Renata

And you use the id to refer to just one of them. Because you only want to show one at a time.

Kieran
Kieran

Aye! You got it!

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.

What now?

Now it’s time to do some more exercises. Yay!

Exercises: A Web page with images

You should do the four recommended exercises. Do the optional exercises if you want more practice.

Exercises in the Explore section are more challenging. You may need to use HTML and CSS that isn’t covered in CoreDogs. Get ready to Google!

Recommended

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:

Output

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.
  • Don’t use text-align. The last image does not go all the way to the right. It just gets indented more.

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

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

Can't find the 'comment' module! Was it selected?

Exercise: The best animal

Download these three images:

Cat

Dog

Horse

Write a page that starts looking like this:

Start state

When the user clicks on the cat or the horse:

Incorrect

When the user clicks on the dog:

Correct

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

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

Can't find the 'comment' module! Was it selected?

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. Here’s some sample output:

Output

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

Can't find the 'comment' module! Was it selected?

Optional

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

Can't find the 'comment' module! Was it selected?

Exploding tennis balls

Most of us dogs like to chase tennis balls. Renata loves it. But you have to be careful.

Create a page that starts off like this:

Start state

Figure 1. Start state

The user clicks on a tennis ball. If the ball is safe, then the page adds one to the number of balls clicked:

One safe click

Figure 2. One safe click

The user clicks another ball. If that’s safe:

Two safe clicks

Figure 3. Two safe clicks

The count keeps going up, as long as the user clicks on safe balls. But if the user clicks on an exploding ball:

Boom

Figure 4. Boom!

How does your code know whether a ball is safe? By the class. Here’s some HTML:

<img class="safe" src="ball.jpg" alt="Toy">
<img class="safe" src="ball.jpg" alt="Toy">
<img class="boom" src="ball.jpg" alt="Toy">
<img class="safe" src="ball.jpg" alt="Toy"><br>

Figure 5. First row of balls

Three of balls have a class of safe. One has a class of boom. Click on a safe ball, and the number of balls gets updated. Click on a boom ball, and the Boom! message appears.

Here’s the photo:

Ball

Upload your solution to your server, and paste the URL below.

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

Can't find the 'comment' module! Was it selected?

Explore

These challenging exercises may use HTML not covered in CoreDogs. Get ready to Google!

Exercise: Tic tac toe game

Create a two-player tic tac toe game. Two people take turns clicking on the grid.

This video explains.

One more thing. If a cell already has an X or O in it, clicking it does nothing.

Here are three images you can use:

X

O

Blank

Before you start, read this article.

Some code that might help:

  <script type="text/javascript">
    var turn = "x";
    var turn_count = 0;
    $(document).ready(function() {

The variables turn and turn_count are declared outside $(document).ready(). They’ll keep their values between clicks.

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

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

Can't find the 'comment' module! Was it selected?

Exercise: New tic tac toe game

Improve the tic tac toe game.

  1. Add a New Game button, that resets the game back to the beginning.
  2. Keep track of the number of games played. Show that on the page.

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

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

Can't find the 'comment' module! Was it selected?