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.

Demo:

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 = "http://www.userinterfaceicons.com/80x80/undo.png";
}

function mouseOutImage()
{
document.getElementById("image").src ="http://www.userinterfaceicons.com/80x80/redo.png";

}
</script>

<img id="image" src="http://www.userinterfaceicons.com/80x80/redo.png" 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
Previous
Next Post »