switching images
Switching images is fairly simple as long as you realize a couple of things: you must preload the image data that you want to switch to into a variable, and if you want to change the image back you have to load the original image data into a variable of its own. You accomplish through the use of the src attribute of the document object. Examine the below example:
<html>
<body>
<img id="image" src="smiley.gif" width="160" height="120">
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>
You can place the JavaScript function that accomplishes this action in any place within the document. However, older browsers require that you place the function in a section of the document that is parsed before the location of the image is stated to be changed. You can use a JavaScript function within the opening and closing SCRIPT tags or you can use a javascript: parameter of any given legal tag within the HTML 4.0 specifications.
To change the image back to the original image, you must use the same src attribute of the document object to do so – simply change the URL of the image file. The browser will load the data and store it until it is triggered with the event handler of your choice.
In the example above we used two variables to store and retrieve the image data. It is entirely possible, and in some cases, desirable, to use one array rather than many variables. Simple declare the array, assign the src attribute in the exact way given above, but use an arrayName[count]= assignment instead of a simple variable declaration.
You would use this technique if you need to change many different images in many different portions of the document, at different times. You should use variables if you wish to change many images that are the same at the same time – the image data stored in the variable will be used repeatedly.
|