Working with images in JavaScript

JavaScript uses the image object to preload images, create rollovers, and it even can create slide shows and animations.

Table of content:

  • Preloading
  • Rollover

Preloading

Preloading an image means that the image is in the browser’s cache before it is called in the HTML or JavaScript code in the browser. This way the image will be shown quicker to the viewer.

For example, if you want to display a rollover then you may want to preload the images. If the viewer moves the mouse over an image and he has to wait for the second image to load then the intended effect is ruined.

<body>

<script>
if (document.images) {
	var pic1 = new Image(120,35);
	pic1.src = "images/pic1.jpg";
	var pic2 = new Image();
	pic2.src = "images/pic2.jpg";
}
</script>

<img src="../images/pic1.jpg" width="299" height="280" 
alt="Image 1"><br>
<img src="../images/pic2.jpg" width="300" height="200" 
alt="Image 2">

</body>

Of course, in this case, the preloading does not serve any purpose. To give preloading a purpose you want the script to show a new image when an event occurs.

Rollover

Image rollovers add some zest to your navigational images. When a user moves the mouse over a linked image, the image changes.

<body>

<h3>Rollover</h3>
<p>The image below changes.<br>
Move the mouse over it.</p>

<a href="http://javascript.saigon.ro">
<img src="../images/pic1.jpg" id="image1" 
width="299" height="280" border="0" alt="Image 1">
</a> </body>

The images are used as a navigational link, however, in modern browsers you can access images using document.getElementById(). Now, in JavaScript code we need to get the image element by its id and assign it a new value for the src property on mouseover event and then change it back on mouseout event.

<body>

<h3>Rollover</h3>
<p>The image below changes.<br>
Move the mouse over it.</p>

<a href="http://javascript.saigon.ro">
<img src="pic1.jpg" id="pic1" width="25%" border="0" alt="Image 1">
</a>

<script>
if (document.images) {
var pic1_new = new Image();
pic1_new.src = "pic2.jpg";
}
var im1 = document.getElementById("pic1");
im1.onmouseover = function () { im1.src = pic1_new.src; };
im1.onmouseout =function () { im1.src = "pic1.jpg" };
</script>

</body>

Leave a Reply