Javascript Change Image onmouseover

Updated on 23 Mar 2012,
Published on 30 Jun 2008

Javascript document object provides the method to access the HTML element such as image <img> HTML tag through its id attribute value that can be used to change the image by raising the onmouseover event of <img> tag. You can access the src attribute/property of <img> HTML tag and change the source image dynamically onmouseover event. You can also use the onmouseout event of <img> tag to set back the initial image when user moves the mouse out of the boundary of image element. getElementId method of Javascript document object allows you to access the src arttribute to get or set the URL location of the image for HTML <img> tag. 

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

Syntax of Javascript to change the Src Image onmouseover

document.getElementById("id").src = "url Value";

src property can get or set the value only for the <img> HTML tag. You have to pass the id attribute value of <img> tag to access the src property through Javascript and set the source image dynamically to show the image rollover effect.

Example of Javascript Change Image onmouseover

<html>
<head>
    <title>Javascript Change Image Onmouseover</title>
    <style type="text/css">
        p {
            font-family: Verdana;
            font-weight: bold;
            font-size: 11px;
        }
        
        img {
            cursor: pointer;
        }
    </style>

    <script language="javascript" type="text/javascript">
    <![CDATA[
        function mouseOverImage() {
            document.getElementById("img1").src = "images/green.gif";
        }

        function mouseOutImage() {
            document.getElementById("img1").src = "images/blue.gif";
        }
    ]]>
    </script>
</head>
<body>
    <p>
        This Javascript Example will change the image of<br />
        HTML image Tag onmouseover event.</p>
    <center>
        <img id="img1" 
                src="images/blue.gif" 
                alt="image rollover" 
                onmouseover="mouseOverImage()" 
                onmouseout="mouseOutImage()" />
    </center>
</body>
</html>

Above example code shows the use of onmouseover and onmouseout events of img tag. onmouseover event calls the client end javascript when user moves the mouse pointer over the image element within its boundaries. When user moves the mouse pointer outside the boundary of image <img> tag, the onmouseout event fires the specified client side javascript function. Also CSS selector rule style for <img> tag cursor CSS style with value "pointer" is used to display the Hand cursor when user moves the mouse over the image.

Output:

You can see the output of above discussed codes from the following link:

Change Image Onmouseover

Continue to next tutorial: Javascript Change Link Text Color onmouseover to learn how to rollover the font color of Hyperlink text using JavaScript DOM style properties.

12 Responses to "Javascript Change Image onmouseover"
Hi, Thanks for the code, you just saved me from a couple more hours looking for code that would work. I really appreciate it. My question is: what would the code look like if you had multiple buttons/images? What I have done is this: function mouseOverImage() { document.getElementById("img1").src = "1.jpg"; document.getElementById("img2").src = "2.jpg"; document.getElementById("img3").src = "3.jpg"; } function mouseOutImage() { document.getElementById("img1").src = "1m.jpg"; document.getElementById("img2").src = "2m.jpg"; document.getElementById("img3").src = "3m.jpg"; } It works fine, the problem is that the three buttons change at the same time whenever I "mouseover" any of them. Each button does what it is supposed to do, but the image is loaded in all of them at the same time. Could you help me with this? Thanks, Andy
Ezineasp.net
Hi Andy Here are two alternate methods for JavaScript change image onmouseover. You can create a single JavaScript function that will accept 2 parameters as imgID and imgPath. imgID parameter for associated img tag ID whose image is to be changed. imgPath parameter for passing the image path that is to be set at the time of mouseover event. <script type="text/javascript"> function rolloverImage(imgID, imgPath) { imgID.src = imgPath; } </script> <img src="images/1.gif" alt="image 1" id="img1" onmouseover="rolloverImage(this, 'images/1m.gif');" onmouseout="rolloverImage(this, 'images/1.gif');" /> In the above code snippet this reference is used to pass the element ID as object. You can also use the following function: <script type="text/javascript"> function rolloverImage(imgID, imgPath) { document.getElementById(imgID).src = imgPath; } </script> <img src="images/2.gif" alt="image 2" id="img2" onmouseover="rolloverImage('img2', 'images/2m.gif');" onmouseout="rolloverImage('img2', 'images/2.gif');" /> Hope this will work for you. Good Luck
Hi,

thanks very much for the quick reply. It does solve the problem, it seems, however, there is another problem I just can't figure out how to solve. The image (<img src="images/...) is placed inside a variable like this:

$Message[$i]='
<img src="imagenes/...>';

The problem is that this part does not accept inverted comas of any kind inside the brackets:

onmouseover="rolloverImage('img2','images/2m.gif');"

If I remove this coma: ' , the image doesn't change, if I leave it, there is a syntax error; if I put these comas: " , the image doesn't change. Any idea how to solve this mystery. It is driving me nuts!
Thanks,
Andy
Hi, I think I just solved it by adding \' \' instead of ' or ". Thanks anyway! Andy
Ezineasp.net
Hi Andy Yes this is the right way to use the escape character \' \' with ' comma character while passing the parameters to the JavaScript function. It's gr8 you solved it quickly.
manikandan
Hi, How to insert text in Img Tag in html
can any body help me onmouseover image(top of the page) change the image at the bottom.If any body knows pls send me the code. thanks in advance
Karan
hi I would like to know how to load an image into html by calling it from a xml file.. Any help would be appreciated.. Thanks in advance.
Faras
I am using png images to be displayed on mouseover and mouseout events when I point to a text link. Things are going pretty fine and perfect in all browsers except IE 6 where the images are not changed when I point on the same text.

Here is the HTML code and javascript

<a class="body_links_org" href="recentmatches"><img onload="fixPNG(this)" border="0" id="recentMatchImage" name="recentMatchImage" onmouseover='document.recentMatchImage.src="images/icon1b.png"' onmouseout='document.recentMatchImage.src="images/icon1.png"' src="images/icon1.png" width="24" height="41" /> <br /> <span onmouseover='mouseOver("recentMatchImage", "images/icon1b.png")' onmouseout='mouseOver("recentMatchImage", "images/icon1.png")'> Recent <br /> Matches</span> </a>
function mouseOver(elementid, imagename)
{
document.getElementById(elementid).src = imagename;
}
function mouseOut(elementid, imagename)
{
document.getElementById(elementid).src = imagename;
}

function fixPNG(myImage)
{
if ((version >= 5.5) && (version < 7) && (document.body.filters))
{
var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
var imgTitle = (myImage.title) ?
"title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
var imgStyle = "display:inline-block;" + myImage.style.cssText
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + myImage.width
+ "px; cursor: pointer; height:" + myImage.height
+ "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
myImage.outerHTML = strNewHTML
}
}

Function fixPNG is being used to fix the png issue in IE 6

An instant help in this regard is highly appreciated.
Prashanth
Hi

I did the image changes by mouseover, mouseout events. Actually i m using 3 buttons on leftside. for this 3 buttons i m using 6 images. 3 images for mouseover And other 3 for on mouseout. when mouseover on any 1 of the button on the left side it display an respective image on right side.Image in right side wil remain until mouseover on any other button. So i am using 3 images for rightside on the same <div> position. When any 1 image is dispalyiny other 2 images are hiden. But left side 3 buttons are showing.
This much i did.
here is the code i used

<!-- head part -->
<!-- This script is for hide nd show images on right side -->

<script type="text/javascript" language="JavaScript">
function HideDIV(d)
{
document.getElementById(d).style.display = "none";
}
function DisplayDIV(d)
{
document.getElementById(d).style.display = "block";
}
</script>

<!--This script is for images used for button, I musing 2 images for each button(green nd white) -->

<SCRIPT LANGUAGE="JavaScript">

greenoverview = new Image();
greenoverview.src = "images/iskanwap/green_over.jpg";
whiteoverview = new Image();
whiteoverview.src = "images/iskanwap/white_over.jpg";

greenconstruction = new Image();
greenconstruction.src = "images/iskanwap/green_con.jpg";
whiteconstruction = new Image();
whiteconstruction.src = "images/iskanwap/white_con.jpg";


greenreal = new Image();
greenreal.src = "images/iskanwap/green_real.jpg";
whitereal = new Image();
whitereal.src = "images/iskanwap/white_real.jpg";

construction = new Image();
construction.src = "images/iskanwap/green_over.jpg";

</script>
<style type="text/css">


#top-zone{overflow:visible; width:960px; margin:0 auto; height:20px;} /*Here to keep images hidden in IE mostly*/
<!-- end of head part -->

<!-- Body part -->
<!-- this is the body part, 1st <td> contain 1st button with 2 images -->

<tr><td><span onmouseover="HideDIV('defaultDiv');HideDIV('constructionDiv');HideDIV('realDiv');DisplayDIV('overviewDiv')"

onmouseout="HideDIV('defaultDiv');HideDIV('realDiv');HideDIV('constructionDiv');DisplayDIV('overviewDiv')"style="cursor:pointer"><a

href="overview.php" onMouseOver="image1.src=greenoverview.src;" onMouseOut="image1.src=whiteoverview.src;"><img name="image1"

src="images/iskanwap/white_over.jpg" border=:"0"></a></span></td>

<!-- this <td> tag contain right part images -->

<td rowspan="4">
<div id="defaultDiv" class="mybox" style="background-image:url('images/iskanwap/over.jpg'); background-position:left;

background-repeat:no-repeat; border:0"></div>

<div id="overviewDiv" class="mybox" style="display:none;":><span onmouseover="HideDIV('defaultDiv');DisplayDIV('overviewDiv')"

style="cursor:pointer"><a href="overview.php"><img src="images/iskanwap/over.jpg" onmouseover="image1.src=greenoverview.src;"

onmouseout="image1.src=whiteoverview.src;" border="0"/></span></div>

<div id="constructionDiv" class="mybox" style="display:none;":><span onmouseover="HideDIV('defaultDiv');HideDIV('overviewDiv')"

style="cursor:pointer"><a href="construction.php" onMouseOver="image2.src=greenconstruction.src;"

onMouseOut="image2.src=whiteconstruction.src;"><img src="images/iskanwap/CONSTRUCTION2.jpg" border="0" /></span></div>

<div id="realDiv" class="mybox" style="display:none;":><span onmouseover="HideDIV('defaultDiv');HideDIV('overviewDiv')"

style="cursor:pointer"><a href="realestate.php" onMouseOver="image3.src=greenreal.src;" onMouseOut="image3.src=whitereal.src;"><img

src="images/iskanwap/real_estate.jpg" border="0" /></span></div>
</td>
</tr>

<!-- below 2 row contain a 2 button-->

<tr>
<td><span onmouseover="HideDIV('defaultDiv');HideDIV('overviewDiv');HideDIV('realDiv');DisplayDIV('constructionDiv')"

onmouseout="HideDIV('defaultDiv');HideDIV('overviewDiv');HideDIV('realDiv');DisplayDIV('constructionDiv')" style="cursor:pointer"><a

href="construction.php" onMouseOver="image2.src=greenconstruction.src;" onMouseOut="image2.src=whiteconstruction.src;"><img

name="image2" src="images/iskanwap/white_con.jpg" border=0></a></span></td>
</tr>
<tr>
<td><span onmouseover="HideDIV('defaultDiv');HideDIV('overviewDiv');HideDIV('constructionDiv');DisplayDIV('realDiv')"

onmouseout="HideDIV('defaultDiv');HideDIV('overviewDiv');HideDIV('constructionDiv');DisplayDIV('realtDiv')" style="cursor:pointer"><a

href="realestate.php" onmouseover="image3.src=greenreal.src;" onmouseout="image3.src=whitereal.src;"><img name="image3"

src="images/iskanwap/white_real.jpg" border=0/></a></span></td>
</tr>

<!-- End of body part -->

So now wat i want is when mouse out from this whole part, it should behave like a slide show. I mean when 1st button highlighting by changing image of the button, along with that it should display respective image on right side div position. when mouse over on any button it should behave as before.

Please any one knows the code for my logic. help in this regards..
Madhura
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
function mouseover(id)
{
if (id =='g1')
{
document.getElementById("g1").src = "images/Our Heritage 02.gif";
document.getElementById("g2").src = "images/D&B Today Tomorrow 01.gif";
document.getElementById("g3").src = "images/About D&B India 01.gif";
}
else if(id =='g2')
{
document.getElementById("g1").src = "images/Our Heritage 01.gif";
document.getElementById("g2").src = "images/D&B Today Tomorrow 02.gif";
document.getElementById("g3").src = "images/About D&B India 01.gif";
}
else
{
document.getElementById("g1").src = "images/Our Heritage 01.gif";
document.getElementById("g2").src = "images/D&B Today Tomorrow 01.gif";
document.getElementById("g3").src = "images/About D&B India 02.gif";
}
}


function mouseout(id)
{
if (id =='g1')
{
document.getElementById("g1").src = "images/Our Heritage 01.gif";
}
else if(id == 'g2')
{
document.getElementById("g2").src = "images/D&B Today Tomorrow 01.gif";
}
else
{
document.getElementById("g3").src = "images/About D&B India 01.gif";
}
}

</script>
</head>

<body>
<table width="700" border="0">
<tr>
<td><div align="left">
<a href="#" onmouseover="mouseover(g1)" ><img id="g1" src="images/Our Heritage 02.gif" width="94" height="21" border="0" /></a>
<a href="#" onmouseover="mouseover(g2)" ><img id="g2" src="images/D&B Today Tomorrow 02.gif" width="128" height="21" border="0" /></a>
<a href="#" onmouseover="mouseover(g3)" ><img id = "g3" src="images/About D&B India 02.gif" width="102" height="21" border="0" /></a></div></td>
</tr>
</table>
</body>
</html>


hello,I've written this code for rollover.but it is not showing effect for next 2 images.I have used condition check over there,so that,only image that has been rolled over will change not all.but I'm not getting that effect.can anyone tell me tha problem?
This is the shortest and simplest way to do that. I hope this helps.
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers