Follow this blog

Wednesday, March 4, 2009

Dynamically change image in js

It is possible to dynamically change image using js (javascript) on web. For example we can display one image when mouse pointer is over image and other image when mouse pointer is no more over image. To find more javascript effects like changing image on this page click on the link.

If you want to change image after user click on image or button then read: alternate image after onclik event.

To do this we will use javascript events (onmouseover and onmouseout) and src attribute.


Example of change src atribute of image with javascript

In this demo when you move mouse over image the arrow change side. It is achieved with changing src property. When mouse is over image we see undo.png and when mouse is out of image we see redo.png.

Here is code used for demo:

<script language="javascript" type="text/javascript">

function mouseOverImage()
document.getElementById("image").src = "";

function mouseOutImage()
document.getElementById("image").src ="";


<img id="image" src="" alt="Example of change src atribute of image with javascript" onmouseover="mouseOverImage()" onmouseout="mouseOutImage()">

Computers & Programming > Programming
onmousemove event occurs when the mouse pointer is moved. Each time a user moves the mouse one pixel, a mousemove event occurs.

onmouseout event occurs when the mouse pointer moves away from a specified object.

For demo purposes are used free icons from user interface icons.

For blogger users:
To include js in post see instructions about javascript in blogspot post. Important is that js code should be in one line.

Related articles:
Show and hide html elements


Anonymous said...

I recently came accross your blog and have been reading along. I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.


Anonymous said...

Nice code. Thanks for the tip. The only thing I would love to know is what the code would look like for several images/buttons. Would you be able to give me a hand?

Mark said...

I will answer you for few days.

Mark said...

Here is code, click on first button and two images will be changed. Click on second button and old two images will appear. Hope this code help you.


<script type="text/javascript">
function newImages()

function oldImages()



<img id="image1" src="" alt="Example of change src atribute of image with javascript">
<img id="image2" src="" alt="Example of change src atribute of image with javascript">
<button id="butChangeImg" onclick="newImages()">New images</button>
<button id="butChangeImg" onclick="oldImages()">Old images</button>