JavaScript

Switching the src Attribute of an Image (img) Without jQuery

There are numerous ways to dynamically switch images on a web page. In this tutorial, we’ll explore how to change the src attribute of an image (img tag) using JavaScript’s document.images[].src, without relying on jQuery.

Many developers implement image-switching functionality using libraries like jQuery for simplicity. However, achieving the same functionality with just JavaScript can improve page performance and deepen your understanding of JavaScript basics. This method is particularly suitable for small projects or implementing simple features.

We will break down each step for clarity, so please follow along until the end.

CSS Code for Switching the `src` Attribute of an Image

First, let’s define the style of the images using CSS. This stylesheet controls the appearance of images and links. CSS handles the visual aspects, and by integrating it with JavaScript, users can smoothly switch images.
Here, we will use the following CSS code. This code provides a simple styling template, but you are free to customize it as needed.

<style type="text/css">
<!--
body{
	margin:0;
	padding:0;
}
h1{
	font-size:16px;
	font-weight:normal;
	line-height:2.0em;
	text-align:center;
	padding:15px 0;
}
#idWrap{
	width:600px;
	margin:0 auto;
	text-align:center;
}
#idLink{
	width:180px;
	text-align:center;
	margin:0 auto;
	padding-top:10px;
}
#idLink a{
	text-decoration:none;
	color:#333333;
	font-size:18px;
}
#idLink a:hover{
	text-decoration:underline;
	color:#666666;
	font-size:18px;
}
-->
</style>

This CSS adjusts the layout of the page, including the style of the h1 tag and the image links. It ensures that the entire page is well-aligned, providing a smooth foundation for switching images.

Switching the `src` Attribute of an Image with JavaScript

Next, let’s implement the JavaScript code to switch images. Here, we’ll use a function called `chgImg()`. This function takes two arguments: the filename of the image to be displayed and the `name` attribute of the `img` tag.

<script type="text/javascript">
function chgImg(fileName,imgName){
	document.images[imgName].src = fileName;
}
</script>

This JavaScript code dynamically changes the `src` attribute of the corresponding `img` tag based on the specified image filename. Specifically, `document.images[]` references all the image elements on the page and selects the image with the specified `name` attribute. It then updates the `src` attribute to the new filename.
For instance, when the user clicks on “Image 1,” the image changes to i01.jpg. Similarly, clicking on “Image 2” switches the image to i02.jpg. This simple code allows for dynamic image switching.

Switching the `src` Attribute with HTML

Now, let’s create the HTML structure to call the JavaScript function and switch images. The following HTML code allows images to switch when the user clicks on an `a` tag (link).

<div id="idWrap">
    <h1>Click the number links below to switch to the corresponding image.</h1>
    
    <div align="center"><img name="chg" src="i01.jpg" alt="" width="300" height="300" /></div>
    
    <div id="idLink">
    <a href="javascript:void(0)" onclick="chgImg('i01.jpg','chg');">1</a> <a href="javascript:void(0)" onclick="chgImg('i02.jpg','chg');">2</a> <a href="javascript:void(0)" onclick="chgImg('i03.jpg','chg');">3</a> <a href="javascript:void(0)" onclick="chgImg('i04.jpg','chg');">4</a> <a href="javascript:void(0)" onclick="chgImg('i05.jpg','chg');">5</a>
	</div>
    
</div><!--/idWrap-->

In this code, clicking the a tag triggers the chgImg() function, switching the src attribute of the img tag to the corresponding image. The image linked to the clicked link is displayed, making the interface intuitive and easy to use.

The initial image is set with the img tag. In this example, i01.jpg is the default image, and clicking on a link switches it to another image.

Important Considerations When There Are Many Images

If you have a large number of images or if the image file sizes are large, loading all images at once can slow down the page load time. In such cases, consider using techniques like “lazy loading,” which loads images only when needed, or preloading images ahead of time.
This approach allows for a responsive dynamic image switching experience. For large gallery sites or sites that use rich media, these optimizations are crucial to maintaining performance while offering a user-friendly interface.

Demo Page for Switching the `src` Attribute of an Image Without jQuery

You can see a demo of the method introduced here on the following page, where images switch dynamically without using jQuery.

Demo page for switching the src attribute of an image without using jQuery

In this demo, multiple images are displayed, and clicking on the links allows you to see the images switch. This lightweight approach is particularly effective when dealing with few images or simple page setups.

Additional Information for Beginners

1. What is `document.images[]`?

By using `document.images[]` in JavaScript, you can access all the image elements (`img` tags) on the page. Each image on the page is stored in this array, and you can specify a particular image using either the index number or the `name` attribute. For example, `document.images[0]` refers to the first declared image on the page, while `document.images[‘chg’]` specifies the image with the `name` attribute of `chg`.

2. About the `name` Attribute in `img` Tags

In HTML, the `img` tag can have a `name` attribute. This `name` attribute serves as a label that allows JavaScript to easily reference the image. While the `id` attribute is used with other HTML elements, the `name` attribute is convenient for interaction with JavaScript. By using this attribute, you can uniquely identify and manipulate the image easily.

3. Role of `javascript:void(0)`

By writing `href=”javascript:void(0)”` in an anchor (`a`) tag, you ensure that the link doesn’t reload the page or navigate elsewhere, and only the JavaScript function is executed. This is useful when you want to trigger JavaScript actions without affecting the page’s state. `void(0)` means “return nothing,” ensuring it doesn’t affect the page’s behavior.

4. How to Use the `onclick` Event

The `onclick` event handler is used to execute a JavaScript function when the user clicks a link or button. In this example, each link is assigned an `onclick` event that calls the `chgImg()` function. Every time a link is clicked, the corresponding image is displayed, allowing for real-time updates based on user interaction.

5. Preloading Images

To enhance the performance of your page, preloading images that aren’t immediately visible can help. This technique ensures that the images are already loaded when the user clicks a link, providing a seamless experience without delays.
Here’s a simple example of preloading images using JavaScript:

function preloadImages() {
  const images = ['i01.jpg', 'i02.jpg', 'i03.jpg', 'i04.jpg', 'i05.jpg'];
  for (let i = 0; i < images.length; i++) {
    const img = new Image();
    img.src = images[i];
  }
}
window.onload = preloadImages;

This code allows you to preload specified image files in the background when the page is loaded. It prevents delays when the user switches images.

Conclusion

In this tutorial, we introduced a method for dynamically switching the `src` attribute of images using only JavaScript, without jQuery. Leveraging `document.images[]` to manipulate images with a `name` attribute is lightweight and efficient.
When dealing with many images, consider using techniques like preloading or adding animations to enhance the user experience. These technologies can be applied to a wide range of interfaces, from simple image switching functionality to more complex interactions.

Start by mastering the basic image-switching technique, then challenge yourself with performance improvements and animation techniques.

*Please use this content at your own risk.
*Do not copy the Google Analytics tag from the demo page’s head tag.