Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
From the author of Creating the Image Path

Creating the Image Path

Because the images are in a folder called images at the same level as the page, we need to first assemble the relative path to the selected image. It needs to look like this:

images/pic5.jpg

All we need to do is replace the number in this path with the random number we just generated. To do this, we'll concatenate (join together) two strings of text containing the unchanging part of this path name and the variable holding the image number, using use the plus (+) operator. Note that when used between numbers, the + operator adds the numbers together, but when used between text strings, it concatenates them into a single string:

var mySrc = "images/pic" + randomNum + ".jpg"

For clarity, I've added some spaces, which JavaScript ignores. Notice how the + operators and the variable (shown in boldface) are placed between the two strings that contain the unchanging parts of our path name. If the current random number was 2, this line would give us this string:

images/pic2.jpg

Our new variable mySrc now contains the correct URL relative to the page.

  • + Share This
  • 🔖 Save To Your Account