JavaScript Chapter 9 Javascript and Images

Javascript Image Manipulation

You can use Javascript to get at and manipulate images. This may involve creating new images, setting up an array of images, changing the source attribute in the BODY tag, or just doing some simple (or not so simple) animation with them. Let's start with referencing images in the BODY tag.

Images in the BODY tag

Any images you place between the two BODY tags of your HTML pages can be seen by Javascript. This is because whenever you add a picture with the IMG tag it is placed in a collection, which is a sort of array. The first picture that the browser can see, the one closet to the opening BODY tag, is place at position 0 in the collection. The second picture will be placed at position1, the third at position 2, etc.
So let's have a look at some code to see how that works. Create a new web page from your template for this and save it to its own folder. Now download these two pictures (right click each one, and then select "Save Image As" in Firefox, or "Save Picture As" in Internet Explorer). Save them inside of the new folder:
For your web page, move the two SCRIPT tags inside the BODY of the HTML, right at the end:
Basic HTML and SCRIPT code
Now add the following HTML:
HTML tags for two images
So we're adding HTML for two images, a button and a label. Save your work and your web page will look like this:
Web page with two images and a button
What we want to do here is to click the button and get a list all the images in the HTML. We'll print out the list on the label, which has an ID of label_1. The button has an onClick event. The function we want to call is image_test.
Add the image_test function between your two SCRIPT tags.
<SCRIPT LANGUAGE = "Javascript">
function image_test() {
Now add the following line to the function:
var len = document.images.length;
To access all the images in your HTML document you only need the word images. You add it after the dot of document. The length property at the end returns the number of images the document has. To store all the images in an array, the code is this:
var imgs = document.images;
So it's just document.images. The image array will then be stored in the variable to the left of the equal sign.
If you don't want to set up an array, you can just do this:
The code above will return the SRC part of image 0 in your HTML.
Another way to get at all the images is like this:
var imgs = document.getElementsByTagName( 'img' );
You've already used getElementById. But you can also access the elements in your HTML code with getElementsByTagName. Note where all the capital letters are, and that Elements is plural. You use it to access collections, like all the images, or all the hyperlinks, or all the P tags.
Between the round brackets of getElementsByTagName you need the name of the tag you're trying to access. We want to get at all the image tags, so have typed img between two single quotes. (You can use double quotes, if you prefer. And the tag name doesn't have to be in lowercase, like we have it .) If you wanted to access all the hyperlinks on the page, you would type 'a' (or 'A') between the round brackets. The first link would then be at position 0 in the array.
To test all that theory out, add the following code to your script (the lines in bold):
var len = document.images.length;
var imgs = document.images;
document.getElementById("label_1").innerHTML = imgs[0].src;
You should find that a file path and image name will appear in the label:file_path/folder_name/home.jpg
Now change the second line of your Javascript to this:
var imgs = document.getElementsByTagName( 'img' );
After the innerHTML line, change the 0 into a 1. So this:
document.getElementById("label_1").innerHTML = imgs[1].src;
You should find that the file path and image name of the second picture ends up in the label.
You can loop through all the images on your page. Change you code to match ours below:
Javascript code looping through all the images on a HTML page
Once you're done, save your work and refresh. Click the button again and you should find that both file names print out.
Incidentally, if you were wondering why we added the SCRIPT tags at the end of the BODY section, it's because code in the HEAD section gets executed first. When you're experimenting with Javascript and images this could lead to errors as the images in the BODY section may not have finished loading. Our simple code is OK, though, as we're delaying execution by putting all the Javascript in a function.

Creating New Images with Javascript

You can create a new image with Javascript. You then add a SRC part for each image you create.
To get some practice with creating images, we're going to code a simple image scroller. It looks like this:
A simple Javascript image scroller
The idea is that you click one of the arrows and a new picture appears. There are lots of ways to do this, but we're just trying to illustrate the use of Javascript image creation here.
To download the images for this section, click below: (They're just a few snaps we took in London. The arrows were created by us in Photoshop.)
Download the images for this section (96 kilobyte zip file)
Create a new web page for this from your template. Put the images and the webpage in the same folder. Leave the two SCRIPT tags in the HEAD section this time. To arrange everything on the webpage, we've resorted to the use of an old-fashioned table. But you might want to do something fancy with CSS. Here's ours, though:
A simple HTML table
So we have a table with one row. There's three cells in the row (TD). The first cell holds the forward arrow:
<IMG SRC="forward.gif" onClick="scroll_forward()">
The image has had an onClick event added to it. It is calling a function with the name ofscroll_forward. The other arrow image is in cell three. The function for its onClick event is calledscroll_backward. The cell in the middle holds the larger picture:
<IMG SRC="pic_1.jpg" name="pic1">
The SRC says pic_1.jpg. We're going to be changing this SRC when either of the arrows is clicked. Note that we also have a name attribute called pic1. We'll need this to reference the image.
So as the first line of your script, add the following:
var p1 = new Image();
An image is create with the new keyword just after an equal sign. After a space, type the word Image (uppercase "I"). A pair of round brackets follows the word Image.
The p1 variable above will create an image object. To put a picture in it, add this line:
The src after p1stands for source. In other words, the file path to your image. If the web page is in the same folder as the images then the code above will work. If you had your images in a separate folder, but in the same directory as the web page, then the code would be this:
The result is the same: you're storing a picture to go with your new image object.
Set up four more new images, and the pictures to go with them. You code will then look like this:
Javascript  code to create new images
Now that we have created some new images, we can put them into an array. (The reason we're putting them into an array is so that we can scroll through them more easily.) Here's the next line to add to your code:
var imgArray = new Array( p1, p2, p3, p4, p5 );
With this line, each image object takes up a position in an array called imgArray. If you wanted to access image number 2, you'd do it like this (arrays start at 0, remember):
This gets the SRC property from the image object at position 1 in the array, which is our second image.
If you want to switch the big image in the HTML with the image from the array, you'd then put this:
document.pic1.src = imgArray[1].src
To the left of the equal sign, we're referencing pic1. This is the NAME we added to the IMG code. After a dot, we have the SRC property again.
To make the arrows work, we need a bit of logic. Here's the code for the scroll_forward function:
var counter = 0;
var end = imgArray.length - 1;
function scroll_forward() {
if ( counter == end ) {
alert("No more pictures");
else {
document.pic1.src = imgArray[counter].src;
We first set up a counter variable, and set it to 0. We then get the length of the array (how many items it has), and deduct 1 from it. This gets us the last position in the array.)
Inside the function itself is an IF Statement. It checks to see if the counter is the same as the value in the variable called end. This is the maximum value for our array. If we've reached the end then an alert message is displayed saying, "No more pictures".
If the counter isn't at the end of the array then we increment the counter variable. The last line sets the pic1 source to the current image from the array:
document.pic1.src = imgArray[counter].src;
The code for going backwards through the array of pictures is almost the same as for going forwards:
function scroll_backward() {
if ( counter == 0 ) {
alert("Start of pictures");
else {
document.pic1.src = imgArray[counter].src;
There are two differences here. The first one is that the IF Statement now checks if counter has a value of 0. If it does then we display a different message in the alert box. If it's not then we deduct 1 from counter:
To increment a variable by 1 you use the double plus symbols ++. If you want to decrement a counter by 1 then you use the double minus symbols --.
In both versions of the scroll code, though, we access the array of new images by manipulating the index number between the square brackets. This gives a different picture when the arrows are clicked. Here's the whole of the Javascript code:
Javascript image scroller - whole code

Javascript Rollover

Two more useful events are onMouseOver and onMouseOut. (You can have the two words in all lowercase, if you prefer.) As their names suggest, you want something to happen when the mouse pointer moves over or away from something like an image or a hyperlink. Test it out. Move your mouse over the image. Then move it away:

Create a new web page for this from your template. Use the two images that you used previously (right click each one, and then select "Save Image As" in Firefox, or "Save Picture As" in Internet Explorer). Save them to the same folder as your new web page:
For the HTML, add the following between the two BODY tags:
<P><IMG SRC="home.jpg" ID="img1"></P>
<P><A HREF="link1.html">Rollover Link</A></P>
So we have an image with the ID img1. The source is home.jpg. We also have a hyperlink beneath a P tag. When the mouse pointer is over the image we want to swap the it for the one called home2.jpg. When the mouse pointer moves away, we'll swap it back. We'll then do the same with the hyperlink.
Add the following to your IMG tag:
<IMG SRC="home.jpg" ID="img1" onMouseOver="doMouseOver()">
We've added the onMouseOver event to the image. After an equal sign we have the name of the function we want to call.
Move your two SCRIPT tags to the BODY section, right at the end. Now add the doMouseOver function:
Javascript code for an image rollover
The code for the function is just one line:
document.getElementById("img1").src = "home2.jpg";
We're using getElementById. Between the round brackets we have the ID from the IMG tag we set up earlier. After the round brackets we have the SRC (source) property. This tells Javascript that we want to access the source property of an HTML element called img1. To the right of the equal sign, we have the name of the image we want to use as the new SRC property. The code above will work if the image is in the same folder as the web page. If it's in a separate folder (one called images, for example) then we could do this:
document.getElementById("img1").src = "images/home2.jpg";
So try it out. Save your work and load the page in a browser. You should see the image change from the shutters to the eye.
However, when you move your mouse away the eye image will still be there. To remedy that, add the following to the IMG tag:
<IMG SRC="home.jpg" ID="img1" onMouseOver="doMouseOver()" onMouseOut = "doMouseOut()">
We've added an onMouseOut event. This time, the event calls a function with the name doMouseOut.
To switch the image back to the shutters, add the following function to your code:
function doMouseOut() {
document.getElementById('img1').src = "home.jpg";
Again, it's just one line of code. The only difference is the part after the equal sign - we're setting the image back to home.jpg, which is what it was in the first place.
Save your code and refresh the page in your browser. You should see the shutters turn into an eye when you move your mouse pointer over the image, and you should see the eye turn back to the shutters when the mouse moves away.
Now add the onMouseOver and onMouseOut code to your hyperlink:
<A HREF="link1.html" onmouseover="doMouseOver()" onMouseOut = "doMouseOut()">
Rollover Link
Save the changes and refresh in your browser. You should see the rollover effect happen when you move your mouse pointer on then away from the hyperlink.

Javascript timers

You have just seen how to use mouseover and mouseout events to implement a rudimentary animation. But you can use a timer to achieve the same thing - get one or more images to replace others. We'll look at a simple example now using the same two images as previously, the eye and the shutter.
Javascript timers come in two flavours, setInterval and setTimeOut. You use setInterval to execute code every so often, a second, for example; you use setTimeOut to delay execution of your code (don't run the code until 5 seconds have passed).
The timer we'll use is setInterval.
Create a new web page for this from your template. Keep your SCRIPT tags in the HEAD section. Save the page in the same folder as your two images (home.jpg and home2.jpg).
Add the following HTML to the BODY section:
<P><IMG SRC="home.jpg" ID="img1"></P>
<P><INPUT TYPE="button" value=" START " onClick="timer()"></P>
So it's just the home.jpg image with an ID of img1. We also have a button that has an onClick event. The event calls a function with the name timer.
Add this timer function between your two SCRIPT tags, as well as the Boolean variable above it (you'll see what the flip variable does shortly):
var flip = false;
function timer() {
animation = setInterval( "pics()", 1000 );
In between the curly brackets of the function, we have this line:
animation = setInterval( "pics()", 1000 );
This sets up a global variable that we've called animation. (It's global because there's no varkeyword before it. This way, the rest of the code can see what's in it.) To the right of the equal sign, we have this:
setInterval( "pics()", 1000 );
The setInterval method needs two things. The first thing it needs is the name of a function. The second thing it needs is a time in milliseconds (1000 milliseconds = 1 second). The two are separated by a comma. What setInterval does is to execute your function once after every millisecond, or whatever time you put after the comma. If you had 3000 after the comma the function would get execute once every 3 seconds.
The value setInterval returns is an ID. You use this ID to stop the timer, which you'll see how to do soon.
The pics function can now be added to your code. Here it is:
function pics() {
if (flip == false) {
document.getElementById("img1").src = "home2.jpg";
else {
document.getElementById("img1").src = "home.jpg";
flip = !flip;
You'll recognise the document.getElementById lines from the previous section. They are exactly the same. This time, however, they are wrapped up in an IF … ELSE statement. If the Boolean variable called flip is set to false then the home2.jpg image is displayed. If it's set to true then the other image is displayed. The final line is this:
flip = !flip;
This read "flip equals NOT flip." In other words, we're setting the variable to be the opposite of what it currently is. If we don't do this the variable would be stuck on false all the time and the animation wouldn't work.
Try it out. Save your work and load the page in a browser. Click the START button. You should see the eye and the shutter animation play.
However, we need a way to stop it. To do that Javascript has a clearInterval method. In between its round brackets you only need an ID. This is the ID from the left of the equals sign we set up earlier:
animation = setInterval( "pics()", 1000 );
The variable animation is the one that holds the ID, which is returned from setInterval. You then just do this:
clearInterval( animation );
Notice you don't need to set up a variable for clearInterval - just pass it your ID.
So add a new button to your BODY tags. This one:
<INPUT TYPE="button" value=" STOP " onClick="stopTimer()">
Now add the stopTimer function to your code:
function stopTimer() {
Save your work and refresh the page in your browser. Start the animation again. When you're tired of it, click the STOP button. You should find that the animation halts straightaway.

We'll move on from Javascript and images now. However, we'll come back to them in the HTML5 and the Canvas Tag section.