Setting or Replacing Dynamically Images

How to change an image, or the background of the page, once the page is displayed by the browser?

It is very easy, you have just to assign a different file to the src attribute of the img tag. For example, this image is displayed:

Here is the code:

<img src="feed-blue.png" /> 

And you want to replace this image by another one, when some event occurs, for example if the user clicks on the image.
But for assigning a new image file, we need for some knowledge of the DOM's (Document Object Model) interface.

Using DOM

One of the most essential method is getElementsByTagName().
This method allows to access the img tag, by returning the list of all img tags, and images are accessible in the list by the item() method. The right one is selected by its number:

var x = document.getElementsByTagName("img").item(0);

The first image has the number 0, and since we have only one image in our example, this is item(0).

It is even more easy to access a tag if it has an identifier:

<img id="image0" src="feed-blue.png" />

In this case, the tag is accessed directly by the id with the getElementByID() function:

var x = document.getElementById("image0");

Another function of the interface allows to access an attribute and to assign it some value: setAttribute(x, y).
X is the name of the attribute, "src" for us, and y is the value to assign. This may be used even to add an attribute if it does not exist.
For replacing the feed-blue.jpg image by another one, whose filename is feed-orange.png, the instruction is:

x.setAttribute("src", "feed-orange.png");

The JavaScript code

For a better demo of the system, we will alternate the blue and the orange images.
Here is the complete script:

function changeImage(element)
  var x = element.getElementsByTagName("img").item(0);
  var v = x.getAttribute("src");
  if(v == "feed-blue.png")
    v = "feed-orange.png");
    v = "feed-blue.png");
  x.setAttribute("src", v);	

The function may be called by a click on the image:

<img id="image0" src="feed-blue.png" onclick="changeImage(this);" /> 

The function may by called also by a form:

<form name="alternate" method="POST" action="">
   <input type="button" value="Change" onclick="changeImage(document.getElementById("image0");">

Preloading an image

If this is a very big image, it is better to load it first in memory before to display it.
The following code does this:

var z = new Image(); 
z.src = "landscape.jpg"; 

Changing the background of a web page

This is achieved by setting the name of an image to the background attribute of the body tag. The body tag must not be already assigned a background image in the style sheet (CSS).
Here is the complete code:

var z = new Image(); 
z.src = "road.jpg"; 
document.body.background= z.src; 

We need for some button to pass this command, as following (wait for the loading of the image):

View the full JavaScript code.

© 2007-2012