www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: [RESOLVED] Wall of randomly selected images

Hybrid View

  1. #1
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34

    resolved [RESOLVED] Wall of randomly selected images

    I'm so sorry for the baseness of this, I'm starting (again) from total ignorance.

    I'm aiming for a page filled with a stack of images (about 20) - each pulled at random from a set of hundreds, ideally but not necessarily without repetition.

    There are heaps of threads discussing rotating individual images at random but I can't find any referencing a whole wall of images. The plan is for the arrangement to be determined only by the width of the browser so there really doesn't need to be any design to the page - just a long line of pictures, without gaps, wrapped.

    Thanks for reading this, I'm really grateful for any help!

  2. #2
    Join Date
    Jun 2010
    Posts
    3
    What language are you using? Did you want random records from a database referencing image URLs, or random images pulled directly from a folder?

    MySQL has the "ORDER BY RAND()" function which does exactly that. Or else you could always make a custom function in the back-end to randomize how each record is pulled from the DB.

    If you are pulling the images directly from a folder with Javascript, you could name all your images in a series like "image1.jpg", "image2.jpg", etc. Then all you need to do is create a loop that will insert a random image on each iteration.

    Something like:

    var max_num_img = 200;
    var index_record = new Array(); // to keep track of which image was fetched

    for (var i = 0; i < max_num_img; i++){
    var new_rand = Math.random()*200+1;

    // checks if the new number was already used
    while (index_record[new_rand]){
    new_rand = Math.random()*200+1;
    }
    document.write("<img src='images/image" + new_rand + ".jpg' />");
    index_record[new_rand] = true;
    }

    Hope it helps.

    ---
    devut.com

  3. #3
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Amazing! That's spot on, thanks! I should know, but what do I need in the body to refer to this?

  4. #4
    Join Date
    Mar 2010
    Posts
    2,803
    This is one way of doing it.

    This code generates 3 unique random numbers from 0 to the total number of pics (5 for this demo) and display those 3 pics.

    I haven't preloaded the images and you can probaly stream line the code a bit more, but it's getting late in the evening here.

    So maybe use this as a guide:

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
    >
    <
    html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title></title>
     
    <
    style type="text/css">
    <!--
    .
    wallPics {
    width200px}
    -->
    </
    style>
     
    <
    script type="text/javascript">
    <!--
     
    var 
    picPaths = [
    "pic1.jpg",
    "pic2.jpg",
    "pic3.jpg",
    "pic4.jpg",
    "pic5.jpg"];
     
    var 
    randNums = new Array();
     
    function 
    is_in_array(num) {
        var 
    isNumInArray false;
        for(var 
    i=0randNums.lengthi=i+1) {
            if(
    num == randNums[i]) {
                 
    isNumInArray true;
                 
    randNums.length;
            }
        }
        return 
    isNumInArray;
    }
     
    //generate 3 unique random numbers from 0 to 4 (from the 5 pics)
    for(var i=1<= 3i=i+1) {
     do {
         
    randNum Math.floor(Math.random()*picPaths.length)
     }  while(
    is_in_array(randNum));
        
    randNums.push(randNum);
    //end of for loop
     
    /* display the random nums for debugging
    var str = '';
    for(var i=0; i < randNums.length; i=i+1) {
         str = str + randNums[i]+"\n";
    }
    alert(str);
    */
     
    window.onload=function() {
        
    imgElems document.getElementsByTagName('img');
        for(var 
    i=0randNums.lengthi=i+1) {
            
    imgElems[i].src picPaths[randNums[i]];
        }
    }
     
    //-->
    </script>

    </head>
    <body>
     
    <div id="container">
        <img class="wallPics" src="" alt="" />
        <img class="wallPics" src="" alt="" />
        <img class="wallPics" src="" alt="" />
    </div>
     
    </body>
    </html> 
    Last edited by tirna; 07-14-2010 at 06:49 AM.

  5. #5
    Join Date
    May 2010
    Posts
    109
    Sure:

    Try this. The images do not have to be consecutively numbered as in the example. Include as many images as needed.

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Fade-in Image Load</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    	/* declare the path to the images */
    	var imgPath = "./images/";
    
    	/* list your images */
    	var imgSet = [];
    	imgSet[imgSet.length] = "CB1.jpg";
    	imgSet[imgSet.length] = "CB2.jpg";
    	imgSet[imgSet.length] = "CB3.jpg";
    	imgSet[imgSet.length] = "CB4.jpg";
    
    	/* do not edit below this line */
    
    	var pagingImg = [];
    	var IE = navigator.appName == "Microsoft Internet Explorer" ? true : false;		
    
    	function doneLoad(nInterval,nLoadImg){
    
    		clearInterval(nInterval);
    		IE ? nLoadImg.detachEvent('onload', waitLoad, false) : nLoadImg.removeEventListener('load', waitLoad, false);
    	}
    
    	function waitLoad(nLoadImg){
    
    		var nOpacity = 0;			
    		var nInterval = setInterval(function()
    			{
    		 	 nOpacity < 100 ? nOpacity = nOpacity + 5 : doneLoad(nInterval,nLoadImg);
    		 	 IE ? nLoadImg.style.filter = "alpha(opacity = "+nOpacity+")"
    		 	 : nLoadImg.style.opacity = (nOpacity / 100); 
    			}, 5);			 
    	}
    
    	function shuffle(nSet){
    
    		for (r=0; r<nSet.length; r++)
    			{
    			 var tmp1 = parseInt(Math.random()*nSet.length);
    			 var tmp2 = parseInt(Math.random()*nSet.length);
    			 var tmp3 = nSet[tmp1];
    			 nSet[tmp1] = nSet[tmp2];
    			 nSet[tmp2] = tmp3;
    			}		
    	}
    
    	function init(){
    
    		var maxImgDisplay = 4;
    		shuffle(imgSet);
    		var nImg = document.getElementsByTagName('img');
    		for (i=0; i<nImg.length; i++)
    			{
    			 if (nImg[i].className == "pagingImg")
    				{
    				 pagingImg[pagingImg.length] = nImg[i];
    				}
    			}			
    		for (i=0; i<maxImgDisplay; i++)
    			{
    		 	 IE ? pagingImg[i].style.filter = "alpha(opacity = 0)" : pagingImg[i].style.opacity = 0;			
    		 	 pagingImg[i].onload = function()
    				{
    			 	 waitLoad(this);
    				}	
    			 pagingImg[i].src =  imgPath + imgSet[i];			 	
    			}		
    	}
    
    	IE ? attachEvent('onload', init, false) : addEventListener('load', init, false);	
    
    </script>
    </head>
    <body>
    
    	<div>
    		<!-- the number of img tags below, equals the variable maxImgDisplay -->
    
    		<img src=null class="pagingImg" alt="">
    		<img src=null class="pagingImg" alt="">
    		<img src=null class="pagingImg" alt="">
    		<img src=null class="pagingImg" alt="">
    		
    	</div>
    
    </body>
    </html>

  6. #6
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Blimey! Thanks guys - now I have a choice... and I can't choose!

    WebDevGuy's seems attractive, being the shortest and pulling the images from a folder, rather than requiring a full list (image1.jpg, image2.jpg, etc.) in the code itself. Is it too good/simple to be true? I'm still not sure how to actually implement it - any tips there?

    Thanks for the outpouring of help! Brilliant!

  7. #7
    Join Date
    Mar 2010
    Posts
    2,803
    There are a few ways you can do this.

    I've tidied up my code a little.

    You now don't have to enter all 200 path names to the pics.

    But they will all need to be named sequentially with a common stem (which can be anything you like( like pic1.jpg, pic2.jpg etc.

    Then all you need is to edit the value of totalPics from 5 to however mant pics you have.

    If the pics are in a different folder, change the value of imgFolder to point to the folder where your pics are. The demo assume your pics are in the same folder as the html file.

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
    >
    <
    html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title></title>
     
    <
    style type="text/css">
    <!--
    .
    wallPics {
    width200px}
    -->
    </
    style>
     
    <
    script type="text/javascript">
    <!--
     
    var 
    totalPics 5;    //total number of pics in the folder
    var numRandPics 3;  // number of random pics
    var imgFolder './';  //path to images folder
    //---------------------------
     
    var randNums = new Array();
    var 
    picPaths = new Array();
     
    //load the paths to the pics
    for(var i=0totalPicsi=i+1) {
        
    picPaths[i] = imgFolder+'pic'+(i+1)+'.jpg';
    }
     
    //generate 3 unique random numbers
    for(var i=1<= numRandPicsi=i+1) {
     do {
         
    randNum Math.floor(Math.random()*picPaths.length)
     }  while(
    is_in_array(randNum));
        
    randNums.push(randNum);
    //end of for loop
     
    //preload the random images
    var picO = new Array();;
    for(var 
    i=0randNums.lengthi=i+1) {
         
    picO[i] = new Image();
         
    picO[i].src picPaths[randNums[i]];  
    }
     
    //display the random images
    window.onload=function() {
        
    imgElems document.getElementsByTagName('img');
        for(var 
    i=0randNums.lengthi=i+1) {
            
    imgElems[i].src picO[i].src;
        }
    }

    //---------------------------
    // helper function
    function is_in_array(num) {
        var 
    isNumInArray false;
        for(var 
    i=0randNums.lengthi=i+1) {
            if(
    num == randNums[i]) {
                 
    isNumInArray true;
                 
    randNums.length;
            }
        }
        return 
    isNumInArray;
    }
     
    //-->
    </script>

    </head>
    <body>
     
    <div id="container">
        <img class="wallPics" src="" alt="" />
        <img class="wallPics" src="" alt="" />
        <img class="wallPics" src="" alt="" />
    </div>
     
    </body>
    </html> 

  8. #8
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Cheers tirna - that's really smooth! Thanks for sticking with it. I did have one image at the top of the page (a button really) that is now cycling through the random folder with the rest of the images - is there an easy way to isolate and stop that? No worries if it's too late tonight and thanks again for your help.

  9. #9
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Sorted it - sorry, I was lazy!

    Changed
    Code:
    imgElems = document.getElementsByTagName('img')
    to
    Code:
    imgElems = document.getElementsByClassName('wallPics')
    does that seem alright?

  10. #10
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Alright, I'm sorry about this - especially after the great support so far - but the code for the random image wall, as below, isn't working out on MSIE or earlier versions of Safari and Firefox. Is there anything obvious going on? It looks great on current Safari and Firefox...

    Thanks for looking, this feels really, really close!

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">
    .wallPics {
    	margin: 0px;
    	padding: 0px;
    }
    </style> 
    <script type="text/javascript">
    var totalPics = 13;    //total number of pics in the folder
    var numRandPics = 13;  // number of random pics
    var imgFolder = 'images/';  //path to images folder
    
    var randNums = new Array();
    var picPaths = new Array();
    
    //load the paths to the pics
    for(var i=0; i < totalPics; i=i+1) {
        picPaths[i] = imgFolder+'image'+(i+1)+'.jpg';
    }
    
    //generate 3 unique random numbers
    for(var i=1; i <= numRandPics; i=i+1) {
    do {
         randNum = Math.floor(Math.random()*picPaths.length)
    }  while(is_in_array(randNum));
        randNums.push(randNum);
    }
    //end of for loop
    
    //preload the random images
    var picO = new Array();;
    for(var i=0; i < randNums.length; i=i+1) {
         picO[i] = new Image();
         picO[i].src = picPaths[randNums[i]];  
    }
    
    //display the random images
    window.onload=function() {
        imgElems = document.getElementsByClassName('wallPics');
        for(var i=0; i < randNums.length; i=i+1) {
            imgElems[i].src = picO[i].src;
        }
    }
    
    //helper function
    function is_in_array(num) {
        var isNumInArray = false;
        for(var i=0; i < randNums.length; i=i+1) {
            if(num == randNums[i]) {
                 isNumInArray = true;
                 i = randNums.length;
            }
        }
        return isNumInArray;
    }
    </script>
    </head> 
    <body>
    <div>
      <table width="100&#37;" border="0" cellpadding="0" align="center">
        <tr>
          <td width="50%">Website</td>
          <td><img src="arrow.png" width="40" height="40"/></td>
        </tr>
      </table>
    </div>
    
    <div id="container"> 
        <img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/><img class="wallPics" src="" alt=""/> 
    </div> 
    
    </body> 
    </html>

  11. #11
    Join Date
    Mar 2010
    Posts
    2,803
    Quote Originally Posted by Suresure View Post
    Alright, I'm sorry about this - especially after the great support so far - but the code for the random image wall, as below, isn't working out on MSIE or earlier versions of Safari and Firefox. Is there anything obvious going on? It looks great on current Safari and Firefox...

    Thanks for looking, this feels really, really close!
    no problem

    I see you are using getElementsByClassName() which may not exist is some, especially older, browsers.

    You can either check in your code whether the browser has the function or do as I prefer and just include my own function as below.

    Also, it's probably best if the number of <img> elements in your html equals the value of numRandPics.

    The next version will have the <img> elements created dynamically to match the value of numRandPics but I probably won't be able to include that until tomorrow as I will be out for most of today.

    The code below now includes a customised getElementsByClassName() and works in IE8, FF3.6, Opera 10, Safari for Windows 4 and Chrome.

    note: I've changed a few parameter values at the top to suit my own images for testing purposes.

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <
    html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <
    style type="text/css">
    .
    wallPics {
        
    height200px;
     
    margin0px;
     
    padding0px;
    }
    </
    style

    <
    script type="text/javascript">

    var 
    totalPics 5;    //total number of pics in the folder
    var numRandPics 3;  // number of random pics
    var imgFolder './';  //path to images folder
     
    var randNums = new Array();
    var 
    picPaths = new Array();
     
    //load the paths to the pics
    for(var i=0totalPicsi=i+1) {
        
    picPaths[i] = imgFolder+'pic'+(i+1)+'.jpg';
    }
     
    //generate 3 unique random numbers
    for(var i=1<= numRandPicsi=i+1) {
    do {
         
    randNum Math.floor(Math.random()*picPaths.length)
    }  while(
    is_in_array(randNum));
        
    randNums.push(randNum);
    }
    //end of for loop
     
    //preload the random images
    var picO = new Array();;
    for(var 
    i=0randNums.lengthi=i+1) {
         
    picO[i] = new Image();
         
    picO[i].src picPaths[randNums[i]];  
    }
     
    //display the random images
    window.onload=function() {
        
    imgElems getElementsByClassName(document,'img','wallPics');
        for(var 
    i=0randNums.lengthi=i+1) {
            
    imgElems[i].src picO[i].src;
        }
    }
     
    //helper function
    function is_in_array(num) {
        var 
    isNumInArray false;
        for(var 
    i=0randNums.lengthi=i+1) {
            if(
    num == randNums[i]) {
                 
    isNumInArray true;
                 
    randNums.length;
            }
        }
        return 
    isNumInArray;
    }
     
    function 
    getElementsByClassName(oElmstrTagNamestrClassName)  {
        var 
    arrElements = (strTagName == "*" && oElm.all)? oElm.all oElm.getElementsByTagName(strTagName);
        var 
    arrReturnElements = new Array();
        
    strClassName strClassName.replace(/\-/g"\\-");
        var 
    oRegExp = new RegExp("(^|\\s)" strClassName "(\\s|$)");
        var 
    oElement;
        for(var 
    i=0i<arrElements.lengthi++)
        {
            
    oElement arrElements[i];
            if(
    oRegExp.test(oElement.className))
            {
                
    arrReturnElements.push(oElement);
            }
        }
        return (
    arrReturnElements)
    }
    </script>
    </head> 
    <body>
    <div>
      <table width="100%" border="0" cellpadding="0" align="center">
        <tr>
          <td width="50%">Website</td>
          <td><img src="arrow.png" width="40" height="40"/></td>
        </tr>
      </table>
    </div>
    <div id="container"> 
        <img class="wallPics" src="" alt=""/>
        <img class="wallPics" src="" alt=""/>
        <img class="wallPics" src="" alt=""/> 
    </div> 
    </body> 
    </html> 
    Last edited by tirna; 07-14-2010 at 06:39 PM.

  12. #12
    Join Date
    May 2010
    Posts
    109
    Thanks for ignoring the code I posted.

  13. #13
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    No Mike! I'm really sorry! I was just looking for a method that didn't require a full list of files/images in the code itself. Could the array used above be included in your solution? I'm sorry - I wish I knew how. I wasn't ignoring your post, just asking which of the three presented might be simplest.

    Any ideas on adding the array or fixing the code as I posted it?

  14. #14
    Join Date
    Apr 2009
    Location
    London, UK
    Posts
    34
    Nice one tirna! I love the thought of the next version - thanks! Time zones mean I'll probably be asleep while you're out - have a good one and thanks again so much for all your help. Magic!

  15. #15
    Join Date
    Mar 2010
    Posts
    2,803
    version 3 (things are much easier now that I am wide awake)

    This is a streamlined version of my previous code.

    It now creates the required number of <img> elements dynamically according to the value of numRandPics.

    This works in IE8, FF3.6, Opera 10, Safari for Window 4 and Chrome.

    If you need more help, post back when you can and if no-one helps in the mean time, I will try to help when I come back tommorow (Friday Melbourne time)

    PHP Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <
    html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <
    style type="text/css">
    .
    wallPics {
     
    margin0px;
     
    padding0px;
    }
    </
    style

    <
    script type="text/javascript">
    var 
    totalPics 5;    //total number of pics in the folder
    var numRandPics 3;  // number of random pics
    var imgFolder './';  //path to images folder
     
    //load the paths to the pics
    var picPaths = new Array();
    for(var 
    i=0totalPicsi=i+1) {
        
    picPaths[i] = imgFolder+'pic'+(i+1)+'.jpg';
    }
     
    //display the random images
    var randNums = new Array();
    window.onload=function() {
        var 
    randNum;
        var 
    picO = new Array(); //store the preloaded images
        //generate unique random numbers and display their pics
     
    for(var i=0numRandPicsi=i+1) {
      do {
           
    randNum Math.floor(Math.random()*picPaths.length)
      }  while(
    is_in_array(randNum));  //this number already used - so generate another.
         
    randNums.push(randNum); //store the random numbers used so far
         //preload the random image
         
    picO[i] = new Image();
         
    picO[i].src picPaths[randNum];
         
    //create the <img> for this pic
         
    imgElem document.createElement("img");
      
    imgElem.setAttribute("src"picO[i].src);
         
    imgElem.setAttribute("alt"'');
      
    imgElem.setAttribute("class"'wallPics');
      
    document.getElementById("container").appendChild(imgElem);
        }
    }
    //------------------------------------
    //helper function
    function is_in_array(num) {
        var 
    isNumInArray false;
        for(var 
    i=0randNums.lengthi=i+1) {
            if(
    num == randNums[i]) {
                 
    isNumInArray true;
                 
    randNums.length;
            }
        }
        return 
    isNumInArray;
    }
     
    </script>
    </head> 
    <body>
    <div>
      <table width="100%" border="0" cellpadding="0" align="center">
        <tr>
          <td width="50%">Website</td>
          <td><img src="arrow.png" width="40" height="40"/></td>
        </tr>
      </table>

    </div><div id="container"> 
     
    </div> 
    </body> 
    </html> 

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles