How to change image with onmouseover in different place that reverts back to default image on the site?

Seb picture Seb · Nov 22, 2012 · Viewed 22.9k times · Source

I'm no expert in this so excuse me if this is very basic but I couldn't find answers.

So I want to have navigation section with categories on the left side of the page. Each category is different site, and each site has it's own unique image on it. ex. category1.htm has defaultpic1.jpg, category 2.htm has defaultpic2.jpg, ....

When I hover on link to category2 in the nav sections I want them to change default image on current site to default image on category2, and then onmouseout I want it to go back to the default one.

Also note my images have different dimensions, different height values.

Basically I know I can change the defaultpic source on every page but I want to use the same script which will always know were to look for the default path and just use it, without the need to change the line in every single category.

Sorry if I'm not very clear on that but I try my best.

I have this (removed everything else so I just paste what I need help with):

<html>
<head>
<script type="text/javascript">
          function mouseOverImage2()
{
    document.getElementById("catPic").src='images/defaultpic2.jpg'; document.images['catPic'].style.width='280px'; document.images['catPic'].style.height='420px';;
}  function mouseOverImage3()
{
    document.getElementById("catPic").src='images/defaultpic3.jpg'; document.images['catPic'].style.width='280px'; document.images['catPic'].style.height='266px';;
}
function mouseOutImage()
{
    document.getElementById("catPic").src='???'; //here's what I don't know what to put
}
</script>
</head>
<body>
<div class="nav">
          <ul>
              <li><a href="subcategory2.htm" onmouseover="mouseOverImage2()"
    onmouseout="mouseOutImage()">Subcategory One</a></li>
              <li><a href="subcategory3.htm" onmouseover="mouseOverImage3()"
    onmouseout="mouseOutImage()">Subcategory 2</a></li></ul>
</div>
<div>
              <img id="catPic" src="images/defaultpic1.jpg" width="280" height="420" alt="">
            </div>
</body>
</html>

Answer

StuartLC picture StuartLC · Nov 22, 2012

You need to store the old image src in a temporary variable, or element somewhere, for example, using a global:

var originalImage;
function mouseOverImage2()
{
    originalImage = document.getElementById("catPic").src; 
    ... 

And then restore it on the mouse out:

document.getElementById("catPic").src=originalImage;

Edit

You can cache other properties (height, width) in much the same way. One thing to note is not to mix old-school html height and width attributes with style height and width - this will lead to confusion.

I've update the Fiddle here