4

I'm using a script on the homepage of a website for a photographer which displays an image selected at random from an array. I have found two different scripts which perform this function. I'd like to know which script is preferable and if it has been written correctly or can be improved. I wonder if it is possible to include a function that would prevent the same image from loading twice until all of the images in the array have been used. Thanks for taking a look.

Version 1

    <script type="text/javascript">
    <!--
    var theImages = new Array() 

            theImages[1] = 'portrait/fpo/01.jpg'
            theImages[2] = 'portrait/fpo/02.jpg'
            theImages[3] = 'portrait/fpo/03.jpg'
            theImages[4] = 'portrait/fpo/04.jpg'
            theImages[5] = 'portrait/fpo/05.jpg'
            theImages[6] = 'portrait/fpo/06.jpg'
            theImages[7] = 'portrait/fpo/07.jpg'
            theImages[8] = 'portrait/fpo/08.jpg'
            theImages[9] = 'portrait/fpo/09.jpg'
            theImages[10] = 'portrait/fpo/10.jpg'

    var j = 0
    var p = theImages.length;
    var preBuffer = new Array()
    for (i = 0; i < p; i++){

            preBuffer[i] = new Image()
            preBuffer[i].src = theImages[i]
    }
    var whichImage = Math.round(Math.random()*(p-1));
    function showImage(){

            document.write('<img src="images/'+theImages[whichImage]+'">');
    }
    // -->
    </script>

    <table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
    <tr valign="middle"><td align="center">

            <a href="index.html"><script type="text/javascript">showImage();</script></a>

    </td></tr>
    </table>

Version 2

    <script type="text/javascript">
    <!--
    var ic = 11; // Number of alternative images
    var xoxo = new Array(ic); // Array to hold filenames

    xoxo[0] = "images/portrait/fpo/01.jpg"
    xoxo[1] = "images/portrait/fpo/02.jpg"
    xoxo[2] = "images/portrait/fpo/03.jpg"
    xoxo[3] = "images/portrait/fpo/04.jpg"
    xoxo[4] = "images/portrait/fpo/05.jpg"
    xoxo[5] = "images/portrait/fpo/06.jpg"
    xoxo[6] = "images/portrait/fpo/07.jpg"
    xoxo[7] = "images/portrait/fpo/08.jpg"
    xoxo[8] = "images/portrait/fpo/09.jpg"
    xoxo[9] = "images/portrait/fpo/10.jpg"
    xoxo[10] = "images/portrait/fpo/11.jpg"

    function pickRandom(range) {
        if (Math.random)
            return Math.round(Math.random() * (range-1));
        else {
            var now = new Date();
            return (now.getTime() / 1000) % range;
        }
    }
    // Write out an IMG tag, using a randomly-chosen image name.
    var choice = pickRandom(ic);
    // -->
    </script>

    <table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
    <tr valign="middle"><td align="center">

            <a href="index-alternate.html"><script type="text/javascript">document.writeln('<img src="'+xoxo[choice]+'" >');</script></a>

    </td></tr>
    </table>

D Benway
  • 65
  • 1
  • 2
  • 10
  • You're missing one of your pictures in the first version, fyi. I would go with 2. 1 is loading all of the images up front (more useful if you'll be changing images while the page is loaded). So it uses more bandwidth and will make your page load slower. – John Hoven Apr 27 '11 at 19:13

2 Answers2

3

This code will load images randomly and his respective link to load.

<html>
<head/>
<title>Jorgesys Android</title>
<script type="text/javascript">
  var imageUrls = [
       "http://stacktoheap.com/images/stackoverflow.png"
     , "http://stacktoheap.com/images/stackoverflow.png"
     , "http://stacktoheap.com/images/stackoverflow.png"
     , "http://stacktoheap.com/images/stackoverflow.png"
     , "http://stacktoheap.com/images/stackoverflow.png"
     , "http://stacktoheap.com/images/stackoverflow.png"
  ];
 var imageLinks = [
       "http://www.stackoverflow.com"
      , "http://www.reforma.com"
       , "http://www.nytimes.com/"
      , "http://www.elnorte.com/"
      , "http://www.lefigaro.fr/international/"
     , "http://www.spiegel.de/international/"    
  ];

  function getImageHtmlCode() {
    var dataIndex = Math.floor(Math.random() * imageUrls.length);
    var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
    img += imageUrls[dataIndex];
    img += '\" alt=\"Jorgesys Android\"/></a>';
    return img;
  }
</script>
</head>
<body bgcolor="black">
<script type="text/javascript">
  document.write(getImageHtmlCode());
</script>
</body>
</html>
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

Decided to make it an answer.

FYI... You're missing one of your pictures in the first version, fyi.

I would go with 2. 1 is loading all of the images up front (more useful if you'll be changing images, doing a slide-show type thing). So it uses more bandwidth and will make your page load slower.

2 looks fine but I might change pickRandom(ic) to pickRandom(xoxo.length) so you don't have to forget about updating ic as you add more images.

You would probably want either to create a cookie for the user (lastImageIndex) to loop through the items. If cookies aren't available, just use a random image. Otherwise, start at a random image. Then each time accessed with the cookie increment. When you reach the length, go back to 0.

function getCookieValue(choice){
  // read cookie here, if found, parseInt(cookieValue,10) and assign to choice

  // Then return choice (either original value or updated)
  return choice;
}

var choice = pickRandom(xoxo.length);
choice = getCookieValue(choice);
// Check if it correspond to an image
if (choice >= xoxo.length) choice = 0;

// Store the cookie here.  Store choice++

That description is slightly different than what you asked for, since its per user, but I'd bet it gives you more the result you are looking for.

John Hoven
  • 4,085
  • 2
  • 28
  • 32
  • That's very helpful. Thanks benjynito. If I change pickRandom(ic) to pickRandom(xoxo.length) as you suggest, what would I change "var ic = 179; // Number of alternative images" and "var xoxo = new Array(ic); // Array to hold filenames" to? – D Benway Apr 27 '11 at 20:05
  • You could probably just get rid of ic and make var xoxo = new Array(); Or var xoxo = new Array(17); All its doing is declaring the initial size of the array. It won't prevent/matter if you go over. – John Hoven Apr 27 '11 at 20:31
  • You're welcome, was the cookie idea enough information to get you started on that? My algorithm would be: function getCookieValue(choice){ // read cookie here, if found, assign to choice // Then return choice (either original value or updated) return choice; } var choice = pickRandom(xoxo.length); choice = getCookieValue(choice); // Check if it correspond to an image if (choice >= xoxo.length) choice = 0; // Store the cookie here. Store choice++ – John Hoven Apr 27 '11 at 20:52
  • Yes, your suggestion on using cookies makes sense to me in concept. I'll need to do some more research on how to use them before I'll know how to implement their function into the page as I know virtually nothing about how to do this. You've certainly given me a direction to follow. – D Benway Apr 27 '11 at 21:02
  • benjynito, it has occurred to me that a user who visits this page with javascript disabled will see only the html elements (the menu) since I have relied on javascript to display the images. Is there a way to redirect a visitor to an html-based page if he has disabled javascript? – D Benway May 09 '11 at 22:15
  • @D Benway, You can't auto re-direct a user because they don't have script enabled, which would be required to accomplish that goal. See the answer here for an idea: http://stackoverflow.com/questions/993387/noscript-tag-javascript-disabled-warning-and-google-penalty/993461#993461 ....... this basicly starts with a script free version of the page and then adds the functionality on when javascript is available. – John Hoven May 10 '11 at 00:38
  • @DBenway You need to implement the cookie method :) See Read/Write methods at http://www.w3schools.com/js/js_cookies.asp You'll want to set the cookie after this line: // Store the cookie here. Store choice++ – John Hoven Apr 26 '12 at 10:50
  • Are you indicating that I must include the function setCookie as in: function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } after the line: // Store the cookie here. Store choice++ ? How do I implement the cookie on the page? In the tutorial it works as a body onload function. Should I do the same? Thanks – D Benway May 03 '12 at 19:27
  • You just want to define those setCookie / readCookie methods (by coping them in to your script block). Then in the scope that those are available, call those methods with appropriate arguments. Give it a try and if you hit trouble I'll give your page another quick look. – John Hoven May 03 '12 at 19:49
  • See if this helps you along: http://jsfiddle.net/6e724/ Note this is using jQuery and everything in the script section is running in the onload. – John Hoven Jun 11 '12 at 12:17
  • Thanks, I can't tell from the example which function I call on the 'onload' to replicate the jsFiddle page. – D Benway Jun 12 '12 at 00:04
  • Throw this in the head. I had used jquery a few times in that example. – John Hoven Jun 12 '12 at 19:38