Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Script to Randomize Image Order?

    Hello guys,

    I am a js noobie really, and am looking for something specific. I have googled for quite some time now looking for a script to randomize a list of images on refresh.

    For example, If I have 8 images in a line in this order 12345678, when I refresh, I would like them to go into a new random order - 84567321, or anything. What I have found are scripts to allow random new images to appear in place of a single image, which is as close as I have gotten.

    Does anyone know of a script that can do this, or know how to make one? I have looked everywhere, and can't seem to locate one.

    Any help is greatly appreciated.

  • #2
    Senior Coder coothead's Avatar
    Join Date
    Jan 2004
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    1,695
    Thanks
    0
    Thanked 232 Times in 227 Posts
    Hi there Evo-L,

    and a warm welcome to these forums.

    Here is an example for you to try...
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    
    <base href="http://www.coothead.co.uk/images/">
    
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta name="language" content="english"> 
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    
    <title>random image order</title>
    
    <style type="text/css">
    htm,body {
        min-width:1130px;
        background-color:#f0f0f0;
     }
    ul {
        padding:30px 0 0;
        margin:0;
        list-style-type:none;
        text-align:center;
     }
    li {
        display:inline;
        margin:0 5px;
     } 
    img {
        padding:5px;
        border:1px solid #999;
        background-color:#fff;
        box-shadow:#333 6px 6px 8px
     }
    </style>
    
    <script type="text/javascript">
    
      var theImages=[
                     'anim.gif','anim1.gif',
                     'lace1.jpg','anim2.gif',
                     'anim3.gif','logo.jpg',
                     'anim4.gif','anim5.gif'
                     ];
      var theLinks=[
                     'page0.html','page1.html',
                     'page2.html','page3.html',
                     'page4.html','page5.html',
                     'page6.html','page7.html'
                     ];
    
      var ary0=[];
      var ary1=[];
      var k=0
      var c,n;
    
    function randomImgDisplay() {
    
    for(c=0;c<theImages.length;c++) { 
    /* Pre-populate 'ary0' with numbers 0 to theImages.length-1*/
       ary0[c]=c;                              
     }
    	
    while(ary0.length>0) {
    /* Get a random 'ary0' index number */
      n=Math.floor(Math.random()*ary0.length);  
    /* Add 'ary0' value to 'ary1' */
      ary1[k]=ary0[n];                          
      k++;
    /* Remove that element from the 'ary0'. The array gets shorter with each iteration */ 
      ary0.splice(n,1);                       
    
     }
    
    for(c=0;c<theImages.length;c++){
    
    /* replace the image positions */
       document.getElementById('pic'+c).src=theImages[ary1[c]];
       document.getElementById('pic'+c).parentNode.href=theLinks[ary1[c]];
      }
     }
       window.addEventListener?
       window.addEventListener('load',randomImgDisplay,false):
       window.attachEvent('onload',randomImgDisplay)
    </script>
    
    </head>
    <body>
    
    <ul>
     <li><a href="page0.html"><img id="pic0" src="anim.gif" alt=""></a></li>
     <li><a href="page1.html"><img id="pic1" src="anim1.gif" alt=""></a></li>
     <li><a href="page2.html"><img id="pic2" src="lace1.jpg" alt=""></a></li>
     <li><a href="page3.html"><img id="pic3" src="anim2.gif" alt=""></a></li>
     <li><a href="page4.html"><img id="pic4" src="anim3.gif" alt=""></a></li>
     <li><a href="page5.html"><img id="pic5" src="logo.jpg" alt=""></a></li>
     <li><a href="page6.html"><img id="pic6" src="anim4.gif" alt=""></a></li>
     <li><a href="page5.html"><img id="pic7" src="anim5.gif" alt=""></a></li>
    </ul>
    
    </body>
    </html>
    
    coothead
    Last edited by coothead; 02-19-2012 at 08:02 AM.

  • Users who have thanked coothead for this post:

    Evo-L (02-19-2012)

  • #3
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Coothead, thanks!

    Now I have a few questions

    Do I just add this inline in my html code in place of the pictures? What else do I need to modify in the code to make it work for my application?

    I see some style variants, and some img paths - I assume those? I don't want to add any borders or padding or anything, I just want each picture separated by a <br/> tag, or something else so they are stacked on top one another. (They are ads in a side column)

    Thanks so much!
    Last edited by Evo-L; 02-19-2012 at 04:30 PM.

  • #4
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,073
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb Alternative solution

    Alternatively...
    Code:
    <html>
    <head>
    <title> Untitled </title>
    <script type="text/javascript">
    
    function randOrd(){
      return (Math.round(Math.random())-0.5);
    } 
    
    var baseURL = 'http://www.nova.edu/hpd/otm/pics/4fun/';
    var imgList = ['11.jpg','12.jpg','13.jpg','14.jpg','15.jpg','21.jpg','22.jpg','23.jpg'];
    var imageList = [];
    
    window.onload = function() {
      imageList = imgList.sort(randOrd);
      var str = '';
      for (var i=0; i<imageList.length; i++) { 
        str += '<img src="'+baseURL+imageList[i]+'" height="75" width="50"><br>';
      }
      document.write(str);
    }
    
    </script>
    </head>
    <body>
    
    </body>
    </html>

  • Users who have thanked jmrker for this post:

    Evo-L (02-19-2012)

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,611
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by jmrker View Post
    function randOrd(){
    return (Math.round(Math.random())-0.5);
    }
    That gives a bias toward the images staying near their original positions.

    For an unbiased randomized order you can use:

    Code:
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    };
    and then call shuffle instead of sort.

    With the randOrd script you get the least biased result with values around 0.8 rather than 0.5.
    Last edited by felgall; 02-19-2012 at 06:14 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Evo-L (02-19-2012)

  • #6
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thanks guys!

    I tried jmrker's code and it loaded the images and randomized them, but the images replaced the entire webpage.

    Where I am adding the code is into my sidebar, is this correct? I am just copying the code from here, adding my image paths, and inserting it into my sidebar.

    It didn't work right when I did that, so does anyone know how it should be used?

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Another way to shuffle an array:-

    Code:
    shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
    }
    
    var shf = shuffle(imgArray);
    Last edited by Philip M; 02-19-2012 at 06:50 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,073
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Exclamation

    Quote Originally Posted by Evo-L View Post
    Thanks guys!

    I tried jmrker's code and it loaded the images and randomized them, but the images replaced the entire webpage.

    Where I am adding the code is into my sidebar, is this correct? I am just copying the code from here, adding my image paths, and inserting it into my sidebar.

    It didn't work right when I did that, so does anyone know how it should be used?
    Somewhat difficult to determine what your problem is since you have yet to provide any code.
    Show us what you are doing or provide a link to your problem.

  • #9
    Regular Coder
    Join Date
    Aug 2010
    Location
    Now Southern Oregon. I was born and had lived my life in Los Angeles until relocating last year (2010)
    Posts
    209
    Thanks
    52
    Thanked 1 Time in 1 Post

    Here's another approach

    Code:
    /*
    sample image src array
    */
    var display = new Array()
    display[0] = "abstract_box.jpg";
    display[1] = "angel_2.jpg";
    display[2] = "church_2.jpg";
    display[3] = "earrings.jpg";
    display[4] = "File_03.jpg";
    display[5] = "Mary_2b.jpg";
    display[6] = "mary.jpg";
    display[7] = "oval_mirror.jpg";
    display[8] = "photo_frame_1.jpg";
    display[9] = "simple_hanging_window.jpg";
    display[10] = "disp_lantern.jpg";
    display[11] = "table_6.jpg";
    display[12] = "tree_1.jpg";
    display[13] = "wc_7_25_5.jpg";
    display[14] = "wc_7_25_8.jpg";
    display[15] = "wc_7_29_3.jpg";
    function _NEW_WIDGET()
             {
              this.srcPath = '  ';// relative path to your image dir
              this.time;
              this.preload = function(a) // a: image src array
                             {
                              if(document.images)
                                {
                                 var img = new Array();
                                 for(var i = 0; i < a.length; i++)
                                    {
                                     img[i] = new Image();
                                     img[i].src = this.srcPath+a[i];
                                    }
                                 return img;
                                }
                             }
                             
              this.swap = function()
                          { 
                           var a = widgetSrcImg;
                           var c = Math.round((Math.abs(Math.random() * 1.6))*10);
                           if(c < 16)
                             {
                              document.images.dispImg.src = a[c].src;
                             }
                           this.time = setTimeout("Widget.swap()", 2500);
                          }
                         
              this.findImg = function(a)
                             {
                              var displayImg = document.getElementById(a);
                              if(document.addEventListener)
                                {
                                 displayImg.addEventListener('load', this.swap(), false);
                                }
                              else if(document.attachEvent)
                                {
                                 displayImg.attachEvent('onload',  this.swap());
                                }
                             }
             }
    // in main document file:
    var widgetSrcImg = new Array();
    var Widget = new _NEW_WIDGET(); 
    window.onload = function() {  navElement.init();  widgetSrcImg = Widget.preload(display); Widget.findImg('dispImg'); };
    // you also need to define in markup, the image tag, along with an id attribute
    // as well, substitute your own image list

  • #10
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,073
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Lightbulb

    Another version with both options (randOrd and shuffle)
    Code:
    <html>
    <head>
    <title> Shuffle Images </title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=251985
    
    // function randOrd(){ return (Math.round(Math.random())-0.5); } 
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    };
    
    var baseURL = 'http://www.nova.edu/hpd/otm/pics/4fun/';
    var imgList = ['11.jpg','12.jpg','13.jpg','14.jpg','15.jpg','21.jpg','22.jpg','23.jpg'];
    var imageList = [];
    
    function displayImages() {
    //  imageList = imgList.sort(randOrd);         // for simplicity
      imageList = [].concat(imgList.shuffle());    // for more randomness (?)
      var sel = document.getElementById('leftSide').getElementsByTagName('img');
      for (var i=0; i<sel.length; i++) { sel[i].src = baseURL+imageList[i]; }
    }
    window.onload = function() { displayImages(); }
    </script>
    </head>
    <body>
    <div id="leftSide" style="width:100px;float:left">
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    </div>
    <div style="float:left">
    <input type="button" value="Test Shuffle" onclick="displayImages()">
    </div>
    <br style="clear:both">
    </body>
    </html>
    Now that we've shown ours, time for you to show yours!

  • #11
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by jmrker View Post
    Another version with both options (randOrd and shuffle)
    Code:
    <html>
    <head>
    <title> Shuffle Images </title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=251985
    
    // function randOrd(){ return (Math.round(Math.random())-0.5); } 
    Array.prototype.shuffle = function() {
       var s = [];
       while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
       while (s.length) this.push(s.pop());
       return this;
    };
    
    var baseURL = 'http://www.nova.edu/hpd/otm/pics/4fun/';
    var imgList = ['11.jpg','12.jpg','13.jpg','14.jpg','15.jpg','21.jpg','22.jpg','23.jpg'];
    var imageList = [];
    
    function displayImages() {
    //  imageList = imgList.sort(randOrd);         // for simplicity
      imageList = [].concat(imgList.shuffle());    // for more randomness (?)
      var sel = document.getElementById('leftSide').getElementsByTagName('img');
      for (var i=0; i<sel.length; i++) { sel[i].src = baseURL+imageList[i]; }
    }
    window.onload = function() { displayImages(); }
    </script>
    </head>
    <body>
    <div id="leftSide" style="width:100px;float:left">
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    <img src="" height="75" width="50"><br>
    </div>
    <div style="float:left">
    <input type="button" value="Test Shuffle" onclick="displayImages()">
    </div>
    <br style="clear:both">
    </body>
    </html>
    Now that we've shown ours, time for you to show yours!
    Thank you . I didn't have any code so theres nothing for me to show. I ended up using yours, so thanks a lot!

  • #12
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,073
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Thumbs up

    You're both welcome.
    Good Luck!


  •  

    Posting Permissions

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