views:

64

answers:

2

I find myself learning web development. And I just started reading about javascript. As a language, i don't have any trouble with it, but i come across an annoying situation:

I was just going to try my first javascript for a simple action: changing the src attribute of an <img>. So let's imagine i have this code in index.html:

<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

    <script type="text/javascript" language="javascript" charset="utf-8">
      function activate(id)
      {
        document.images(id).src ="home-on.jpg";
      }

      function deactivate(id)
      {
        document.images(id).src ="home-off.jpg";
      }
    </script>
  </head>

  <body id="ID">
    <img id="home" src="home-off.jpg"
    onmouseover="activate('home')"
    onmouseout="deactivate('home')"/>
  </body>
</html>

The code works perfectly on google chrome (swapping the image when the mouse is over, and out). But I have no luck with firefox. Any help? advice?

+6  A: 

You're using the wrong syntax to get the images.

You need to write document.images[id] (With brackets [], not parentheses ())

The document.images collection is an associative array, which is indexed using brackets.
Parentheses are used to invoke a function; I don't know why your code worked in Chrome.

SLaks
Yes, and he can also consider just using document.getElementById(id) as well.
Zurahn
Well thank you. I wasn't aware that document.iamges was an array, I actually thought it was a function! . And yes, I'm a programmer so I know how functions are usually invoked.
Fabzter
You'd be surprised by the average level of some of the beginners here. Also, had you been coming from VB, the distinction would have been new to you.
SLaks
Why? is the average level too slow or too high?
Fabzter
For some people, far too low.
SLaks
+1  A: 

SLaks has entered the correct answer for this particular question.

However, you will find in JavaScript that there is a lot of cases like this where incorrect syntax will work in one browser but not in the next. For ensuring that you maintain cross browser compatibility in JavaScript you might find a library such as jQuery very handy. Not only does it attempt to ensure that your JavaScript code is compatible with all browsers, it also extends a lot of great functionality.

HTH

Chris Nicol
Than you, I was already thinking in using jQuery, but I wanted to start from the ground before getting into frameworks. :-)
Fabzter