views:

58

answers:

4

Why doesn't this piece of code swap images on mouse-over as intended?:

<a href="#" onMouseOver="
 if (document.the_image.src == '01.jpg')
 {
  document.the_image.src = '02.jpg';
 }
 else if (document.the_image.src == '02.jpg')
 {
  document.the_image.src = '03.jpg';
 }
 else
 {
  document.the_image.src = '01.jpg';
 }
 ">
Some image</a><br>
+1  A: 

Most likely in the rendered HTML, the image source is an absolute URL, so the src is probably "http://mydomain.com/01.jpg"

To test this, try setting an alert() in your code to see what the actual src value is

You should probably also put that code in a function, that's a lot of javascript to put in inline HTML.

jaywon
+1 for the solution and for working in Hawai. I wish I were there :-)
Claudio Redi
@claudio - lol, thanks i can't complain ;)
jaywon
jaywon, your comments make a lot of sense to me. Thanks a lot.
alex_wang
+1  A: 

To complement @jaywon answer, if that is the case you can use this to ensure that it is matching regardless of absolute or relative URL.

if (document.the_image.src.indexOf('01.jpg') > 0) {
...
}
Dustin Laine
+1 good suggestion!
jaywon
A: 

My reputation is 6. I need to raise it to 10 in order to post my complete code, which include image tags and hence can't get through stackoverflow.com's spam prevention mechanism. Any suggestion for ways to achieve that? Thanks.

alex_wang
A: 

Finally, I've figured out how to post the complete code. Thanks very much!:

<HTML>
<head>

<title></title>
<script language="javascript">
    var name = prompt('What is your name?', '');
    document.writeln('Welcome, ' + name + '.');
</script>
</head>


<body>

<a href="#" onMouseOver="
    if (document.the_image.src == '01.jpg')
    {
        document.the_image.src = '02.jpg';
    }
    else if (document.the_image.src == '02.jpg')
    {
        document.the_image.src = '03.jpg';
    }
    else
    {
        document.the_image.src = '01.jpg';
    }
    ">
<img src="01.jpg" name="the_image"></a><br>


</body>

</HTML>
alex_wang
have you tried any of the suggestions so far?
jaywon