0

I got this Javascript code to insert random images on page reload. So far, it works, but want to get into details.

  1. How do I center the images?
  2. How to I insert a different link to a webpage to each images?

    function random_imglink(){
        var myimages = new Array()
        //specify random images below. You can have as many as you wish
        myimages[1] = "http://example.com/picture.jpg"
        myimages[2] = "http://example.com/image.jpg"
        myimages[3] = "http://example.com/graphic.jpg"
    
        var ry = Math.floor(Math.random() * myimages.length)
        if (ry == 0)
            ry = 1
        document.write('<img src="' + myimages[ry] + '" border=0>')
    }
    random_imglink()
    
lokusking
  • 7,000
  • 13
  • 38
  • 51

1 Answers1

0

First, please don't use document.write for this, there are better ways to do it.

Here's a way to generate the image tag within a link and insert it into a container:

HTML

<div id="myContainer"></div>

JS

function random_imglink() {
  var list = [
    {img: "http://example.com/1.jpg", link: "http://example.com/1"},
    {img: "http://example.com/2.jpg", link: "http://example.com/2"},
    {img: "http://example.com/3.jpg", link: "http://example.com/3"}
  ];

  var x = Math.floor(Math.random() * list.length),
      a = document.createElement('a'),
      img = document.createElement('img');
  // insert the img into the link
  a.appendChild(img);
  // Set their attributes
  a.href = list[x].link;
  img.src = list[x].img;

  return a;
}

document.getElementById('myContainer').appendChild(random_imglink());

Add text-align: center to the image container and you're done:

#myContainer{
  text-align: center;
}

Oh, and on a side note, you don't need your if condition, and you can start your array at index 0. Math.random() returns a number between 0 (included) and 1 (excluded). Since you use Math.floor() on it after multiplying it, the result will always be between 0 and the length of your array minus 1 => a valid index if your array has at least one element.

Community
  • 1
  • 1
blex
  • 22,377
  • 5
  • 35
  • 65
  • thanks but it's not working. I am using squarespace. And I know nothing about Javascript. My code works. Would it be possible to show me, with my code provided, how to link each images, and center them. No HTML, No CSS... Just Javascript. – Eric Quenneville Feb 11 '17 at 00:52