Last updated on February 9th, 2022 at 01:42 pm

Change image by modifying image source using Javascript

This javascript will assist you in replacing IMAGE SRC[SOURCE] dynamically ie, the script will change the displayed image when you click the hyperlink. Javascript can do a lot of magic and its main advantage is the DOM properties. We are using onClick event attribute to call a function which in turn replace the image displayed.

I am using two images. One is ‘javascript.jpg’ which loads when we run the html page. The other is ‘mypic.jpg’ which will get dynamically loaded when we click on the “Replace Image” hyperlink.

document.getElementById().src property is used here to change the image source from javascript.jpg to mypic.jpg.

Grab the code here

<head><title>Change image SRC</title>
<script type="text/javascript">
function replaceImage(e) {
    var image = document.getElementById('image');
    image.src = 'mypic.jpg';
    return false;
<a href='#' onClick='replaceImage();' title='Reload image'>Replace Image</a>
 <img width=328 height=153 id="image" src='javascript.jpg'/>


Leave a Reply

Your email address will not be published. Required fields are marked *