0

i am new to java script and i am designing my web site but i want to load a new image on a particular place of my web page when a user hover over the home,here is the code.

        <html>
        <head>
        </head>
        <body>
        <img src="yourImage.jpg" alt="Home" id="image1" onmouseover="image1.src='home.jpg';" onmouseout="image1.src='myImage.jpg';" /> <br />
        <a href="#" onmouseover=image1.src='home.jpg';" onmouseout="image1.src='yourImage.jpg';">Hoover Me!</a>
        </body>
        </html>

This code is not working.Please Help me to find out the error in code.

Naeem Ul Wahhab
  • 2,465
  • 4
  • 32
  • 59

5 Answers5

1

You have to use the method document.getElementById() to get the image object before try to manipulate it:

<body>
    <img src="yourImage.jpg" alt="Home" id="image1" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='myImage.jpg';" /> <br />
    <a href="#" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='yourImage.jpg';">Hoover Me!</a>
</body>

You should consider using JQuery to do this kind of stuff.

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
0
  • image1 doesn't have any meaning. You will need to use document.getElementById('image1').src instead of just image1.src.
  • You're missing the starting quote for the onmouseover attribute of the a tag.
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
0

In addition to not using document.getElementById, you'll also encounter a lag on mouse over, unless the image has been pre-loaded.

MK_Dev
  • 3,291
  • 5
  • 27
  • 45
0

You can not refer to the img as image1.src first you have to assign image1=document.getElementById('image1') then you can refer it as image1.src. There is also a much simpler method to do that. You can also refer to the current image or object as this.src in JavaScript. See the corrected code with changes bellow:

<html>
<head>
</head>
<body>
<img src="yourImage.jpg" alt="[ Home ]" id="image1" onmouseover="this.src='home.jpg';" onmouseout="this.src='myImage.jpg';" /><br />
<a href="#" onmouseover="document.getElementById('image1').src='home.jpg';" onmouseout="document.getElementById('image1').src='yourImage.jpg';">Hoover Me!</a>
</body>
</html>
Naeem Ul Wahhab
  • 2,465
  • 4
  • 32
  • 59
0

To access the img element from it's own inline attributes, you need to use the 'this' keyword:

<img src="yourImage.jpg" alt="Home" id="image1" onmouseover="this.src='yourOtherImage.jpg';" />

Rather than do it inline, you could also use a javascript library, like jQuery, as detailed here, which would give you more flexibility if you want to do more later e.g. add animations, but that's up to you and how much of a challenge you feel like :)

Community
  • 1
  • 1
Matt Gibson
  • 14,616
  • 7
  • 47
  • 79