NewAtThis
NewAtThis

Reputation: 43

JavaScript Thumbnails From Array

I'm trying to work on a website currently that displays pictures with the help of java-script. The way that I have this website set up at the moment, an image is displayed above numbered photo links. Instead of having numbers listed below the pictures, I'd like to have the numbers be thumbnails of the pictures. Is it possible to replace them with images? Any help is appreciated.

This is what I have so far:

var photos = new Array();
var photoindex = 0;

photos[0] = "images/piano.jpg";
photos[1] = "images/guitar.jpg";
photos[2] = "images/studio.jpg";
photos[3] = "images/sheetmusic.jpg";

function backward() {
  if (photoindex > 0) {
    document.images.p.src = photos[--photoindex];
  }
}

function forward() {
  if (photoindex < photos.length - 1) {
    document.images.p.src = photos[++photoindex];
  }
}

for (i = 0; i < photos.length; i++) {
  document.write("<a href=\"javascript: goto(" + i + ");\">" + i + "</a> ");
}

function goto(n) {
  if (n < photos.length && n >= 0) {
    photoindex = n;
    document.images.p.src = photos[photoindex];
  }
}
<br>
<div style="text-align:center;left:5px;">
  <table width="250" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td colspan="3" align="center" valign="top">
        <img src="images/weloveweb.png" name="p" width="250" height="188" id="p" />
      </td>
    </tr>
    <tr>
      <td valign="top"><a href="javascript: backward();">&lt;&lt;</a>
      </td>
      <td valign="top" style="text-align: center">
      </td>
      <td valign="top" style="text-align: right"><a href="javascript: forward();">&gt;&gt;</a>
      </td>
    </tr>
  </table>
</div>

Upvotes: 1

Views: 495

Answers (1)

nem035
nem035

Reputation: 35501

Since your thumbnail urls are stored in the photos array, what you need to do to display a thumbnail instead of its index is to create an img tag with a src attribute containing each thumbnail's url (i.e. photos[i]).

Change:

for (i = 0; i < photos.length; i++) {
  document.write("<a href=\"javascript: goto(" + i + ");\">" + i + "</a> ");
// ------------------------------------------------------------^ change this `i`
}

Into:

for (i = 0; i < photos.length; i++) {
  document.write("<a href=\"javascript: goto(" + i + ");\">" + "<img src=" + photos[i] + "/></a> ");
}

Upvotes: 2

Related Questions