Skip to main content

How to Create an Image Mouse Rollover with JavaScript

JavaScript can be used to change an image when the mouse hovers over it, and change it back when the mouse moves away from it. This page explains how to use JavaScript to create an image mouse rollover.

Step 1: Create an Image Tag

Below is the HTML of an image tag that we will turn into an image rollover.

<img src="someimage.jpg" />

Step 2: Create a JavaScript Function to Change the Image

Below, I have created a function that will change the image's source when the function is called, using the image's src property.

<script type="text/javascript">
function rollover(my_image) {
my_image.src = 'someimage2.jpg';

Step 3: Add the onmouseover Property to the Image

To make the image change with JavaScript when you mouse over it, you must add the onmouseover property to the image tag. In this property, you assign a JavaScript function that should be called when the mouse hovers over the image, as shown below. The function that was defined above will be called when this image is moused over.

<img src="someimage.jpg" onmouseover="rollover(this)" />

However, as you can see, the image doesn't go back to the original version when you move the mouse away from it. One more step is required to change the image back to the original version.

Step 4: Create a Function to Restore the Original Image when the Mouse Moves Away

To make the image return to the way it was, you must add an onmouseout property to the image and define the function that will set the image back to how it was.

<script type="text/javascript">
function mouseaway(my_image) {
my_image.src = "someimage.jpg";
<img src="someimage.jpg" onmouseover="rollover(this)" onmouseout="mouseaway(this)" />

Get help with games!