SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Resident Boozehound simontheak's Avatar
    Join Date
    Jun 2003
    Location
    _root.europe.uk.london
    Posts
    965
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simple Newbie Question

    Hi there,

    I'm trying to display a random image that is selected from an array. What's causing the problem is the route to the image that I'm trying to print to the page. I'm sure I'm doing something wrong with escaping characters ... or something!!

    Anyway, here's the code
    Code:
    <script language="javascript">
    document.write("<img src='images\/" + castlepic[lucky] + "\.gif'" + "width='75' height='70' alt=''></td>";
    </script>
    castlepic is an array I've declared earlier on in my page and lucky is randomly generated number.

    What I'm trying to get is a line that will print out like this:
    Code:
    <img src=images/dog.gif width='75' height='70' alt=''></td>
    Can anyone help me at all?

  2. #2
    ☆★☆★ silver trophy vgarcia's Avatar
    Join Date
    Jan 2002
    Location
    in transition
    Posts
    21,235
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    You don't have to escape slashes or periods in quotes. Your document.write should look more like this:
    Code:
    <script language="javascript">
    document.write("<img src="images/" + castlepic[lucky] + ".gif" + "width='75' height='70' alt=''></td>";
    </script>
    Although, to be honest I wouldn't use a document.write. Try this script out instead:
    Code:
    <script type="text/javascript">
    function setImage(sourceFile) {
      document.getElementById("randomImage").setAttribute("src", sourceFile);
    }
    </script>
    HTML Code:
    <img id="randomImage" src="/default.gif" alt="Random Image" />
    To use it in your current function (the one where you get the value "castlepic[lucky]" from), add this in instead of your document.write:
    Code:
    setImage(castlepic[lucky]);
    Using my method above will be more accessible too, since by default there's an image on screen even if JS is disabled. If javascript is enabled, the image will change to the random one, hopefully when the page loads.

    Hope this helps!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •