Javascript Tutorial -- Creating Dynamic Images



Have you ever visited a photo gallery on-line where there was an image in the center of the page, with "previous" and "next" buttons that would change the image without reloading the whole page? Most likely, this was done with Javascript, since creating simple "animations" such as this was one of the early applications for dynamic HTML. In this lesson, I will show you how to do this yourself.

In the last lesson, we discussed dynamically updating text on your HTML documents by using the "getElementById.innerHTML" method. In this lesson, we introduce another method of "getElementById", the "src" method. getElementById.src retrieves or sets the source URL of an image tag. Consider the following HTML snippet:
        <img src="http://./someimage.jpg" id="changeMe">
      
In this example, we have an <img> tag that references "someimage.jpg" in the same folder as the HTML document that contains this tag, and that has an id of "changeMe". By using the getElementById.src method like this...:
        document.getElementById('changeMe').src = "./someimage2.jpg"
      
...your script can change the image that the <img> tag loads and if you use the getElementById.src method like this...:
        if (document.getElementById('changeMe').src == "./someimage.jpg")
          {
            doSomething()
          }
      
...you can test the "src" attribute of the <img> tag for some value. With this, you can create a script that will rotate through multiple images in response to user input. Here's an example of a script to do this:
        <script type="text/javascript"
          <!--
            function ChangeImage()
              {
                var Images = new Array()
                var i

                Images[0] = 'http://www.gecko-ak.org/Gallery/users/mike/MyCar.jpg'
                Images[1] = 'http://www.geck.org/Gallery/users/mike/T38.jpg'
                Images[2] = 'http://www.gecko-ak.org/Gallery/users/mike/N600LW_2.jpg'

                if (document.getElementById('ChangeMe').src == Images[0])
                  {
                    i = 1
                  }
                else if (document.getElementById('ChangeMe').src == Images[1])
                  {
                    i = 2
                  }
                else
                  {
                    i = 0
                  }

                document.getElementById('ChangeMe').src = Images[i]
              }
          //-->
        </script>
        <p>
          <img src="http://www.gecko-ak.org/Gallery/users/mike/MyCar.jpg" height="480" width="640" id="ChangeMe">
        </p>
        <br>
        <input type="submit" value="change image" onClick="ChangeImage()">
        ...
      
Here is how this script works on-line.