evo2010 Posted April 27, 2013 Share Posted April 27, 2013 HiI am trying to have a number of images that appear randomly at the top of my website. The images must link to separate pages on my site. I have the following code which is working but I am getting alot of repeats, for example the first image may appear 3 or 4 times before the 3rd image appears etc. I have shortened the code to show just 3 images but I have about 15.var total_images = 3;var random_number = Math.floor((Math.random()*total_images));var random_img = new Array();random_img[0] = '<a href="page1.html"><img src="../../images/111.jpg" alt="aaa" title="test1"></a>';random_img[1] = '<a href="page2.html"><img src="../../images/222.jpg" alt="bbb" title="test2"></a>';random_img[2] = '<a href="page3.html"><img src="../../images/333.jpg" alt="ccc" title="test3"></a>';document.write(random_img[random_number]);What do I need to do to this code to ensure that none repeat until all 15 have been displayed. I want it that everytime the page is refreshed or they click through to a new page on the site the header image changes until all 15 have displayed. I also want them to be random, not 1st image, then 2nd image, then 3rd image etc....Any help is much appreciated as I'm new to javascriptThanks Link to comment Share on other sites More sharing options...
Don E Posted April 28, 2013 Share Posted April 28, 2013 (edited) In order to not have any repeats, you have to somehow figure out what images the user has viewed and not let those particular images show up on refreshes/reloads/visits for that particular user. One way to do it would be cookies but JavaScript cookies can be a bit complicated so I suggest something more of the server side language cookiies or sessions. Perhaps there are other ways but you have to somehow "save" the info for what images the user has viewed other than on the current webpage because every time the page is loaded, everything on that page starts over so to speak. So for example, say you created a JavaScript array or object to record the viewed images, when the user refreshes or visits again, the record for the previous viewed image(s) will be lost. Server side language like PHP for example makes handling sessions and cookies pretty easy which allow what you're asking for to be more easier to do. The following is an example: <?phpsession_start(); if(!isset($_SESSION['images'])){ $_SESSION['images'][] = '<a href="page1.html">img1</a>'; $_SESSION['images'][] = '<a href="page2.html">img2</a>'; $_SESSION['images'][] = '<a href="page3.html">img3</a>'; $_SESSION['images'][] = '<a href="page4.html">img4</a>'; $_SESSION['images'][] = '<a href="page5.html">img5</a>'; $_SESSION['randomNums'][] = 0; $_SESSION['randomNums'][] = 1; $_SESSION['randomNums'][] = 2; $_SESSION['randomNums'][] = 3; $_SESSION['randomNums'][] = 4;} ?> <!doctype html><html><head><meta charset="UTF-8"><title>Random Img, no repeat; php</title></head> <body><div id="imgContainer"><?php if(!empty($_SESSION['images']) && !empty($_SESSION['randomNums'])){ $current = array_rand($_SESSION['randomNums'], 1); $img = $_SESSION['images'][$current]; echo $img; array_splice($_SESSION['images'], $current, 1); array_splice($_SESSION['randomNums'], $current, 1);} /*if(empty($_SESSION['images'])) // uncomment for images to start over after all 5 have been viewed{ unset($_SESSION['images']);}*/ ?></div></body></html> Edited April 28, 2013 by Don E Link to comment Share on other sites More sharing options...
Euphorius Posted April 28, 2013 Share Posted April 28, 2013 I am beginner but i think if you use this http://www.w3schools.com/js/js_timing.asp, and you use some infinity loop which shows element from array every 10 seconds or the time you want it to be. I think its possible. As i said im beginner and i am looing for exercises and maybe this will be my next. Link to comment Share on other sites More sharing options...
jeffman Posted April 28, 2013 Share Posted April 28, 2013 This was a fun project. It's seems a little complicated until you realize you can use a lot of off-the-shelf parts. Normally, I'd teach you how to do it, but you really need some experience to fit all this together. 1. Cookies are the way to go, because you need long-term persistence. On the assumption you don't do PHP, I've accessed the cookies using JavaScript. I borrowed well-known cookie functions available at W3Schools. 2. I thought of saving the data as a bit-mask, but I haven't messed with that in years and didn't feel like learning it all over again now. So I chose JSON format. For older browsers, I borrowed a JSON substitute available at Mozilla. 3. I decided to randomize the whole array first (I borrowed this implementation of a well known technique from Stack Overflow) and store the array as a cookie in JSON format. During most page visits, the script will not randomize the array. Instead, it will open the cookie, turn the cookie into an array, pop off the last image in the array, and then store the shortened array as a cookie again. So with every visit, the user gets the next randomized image, until there are no more images in the array. At that point, the script randomizes the array again and stores it for a fresh cycle. 4. A lot of this can be simplified using jQuery methods. Help yourself. <script type="text/javascript"> function setCookie(cookie_name, value, exdays) // props W3Schools { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var cookie_value = escape(value) + ( (exdays == null) ? "" : "; expires=" + exdate.toUTCString() ); document.cookie = cookie_name + "=" + cookie_value; } function getCookie(cookie_name) // props W3Schools { var cookie_value = document.cookie; var cookie_start = cookie_value.indexOf(" " + cookie_name + "="); if (cookie_start == -1) { cookie_start = cookie_value.indexOf(cookie_name + "="); } if (cookie_start == -1) { cookie_value = null; } else { cookie_start = cookie_value.indexOf("=", cookie_start) + 1; var cookie_end = cookie_value.indexOf(";", cookie_start); if (cookie_end == -1) { cookie_end = cookie_value.length; } cookie_value = unescape(cookie_value.substring(cookie_start, cookie_end)); } return cookie_value; } function shuffleArray (myArray) { // props Fisher-Yates var i = myArray.length, j, tempi, tempj; if ( i === 0 ) return false; while ( --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); tempi = myArray[i]; tempj = myArray[j]; myArray[i] = tempj; myArray[j] = tempi; } return myArray; } if (!window.JSON) { // props Mozilla window.JSON = { parse: function (sJSON) { return eval("(" + sJSON + ")"); }, stringify: function (vContent) { if (vContent instanceof Object) { var sOutput = ""; if (vContent.constructor === Array) { for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ",", nId++); return "[" + sOutput.substr(0, sOutput.length - 1) + "]"; } if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; } for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringify(vContent[sProp]) + ","; } return "{" + sOutput.substr(0, sOutput.length - 1) + "}"; } return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent); } }; } function getImage () { var theCookie, img, arr = getImageArray(); theCookie = getCookie("image_cookie"); if (!theCookie || theCookie == "[]") { arr = shuffleArray(arr); } else { arr = JSON.parse(theCookie); } img = arr.pop(); setCookie("image_cookie", JSON.stringify(arr), 365); // expires in 1 year return img; } function getImageArray () { var images = new Array(); images[0] = '<a href="page1.html"><img src="../../images/111.jpg" alt="aaa" title="test1"></a>'; images[1] = '<a href="page2.html"><img src="../../images/222.jpg" alt="bbb" title="test2"></a>'; images[2] = '<a href="page3.html"><img src="../../images/333.jpg" alt="ccc" title="test3"></a>'; images[3] = '<a href="page4.html"><img src="../../images/444.jpg" alt="ddd" title="test4"></a>'; images[4] = '<a href="page5.html"><img src="../../images/555.jpg" alt="eee" title="test5"></a>'; images[5] = '<a href="page6.html"><img src="../../images/666.jpg" alt="fff" title="test6"></a>'; images[6] = '<a href="page7.html"><img src="../../images/777.jpg" alt="ggg" title="test7"></a>'; images[7] = '<a href="page8.html"><img src="../../images/888.jpg" alt="hhh" title="test8"></a>'; return images; }</script> You can put that script in the head of your document or save it as an external file. Wherever you want the randomized image to appear, all you need is this: <script type="text/javascript"> document.write(getImage());</script> Link to comment Share on other sites More sharing options...
evo2010 Posted May 1, 2013 Author Share Posted May 1, 2013 Thank you to all of you that have taken the time to reply, I appreciate it and I apologise for not getting in touch sooner but I have been working on another project. I now have some time to go back to this so will look into what you have all said and have a go, wish me luck! -though i'm most likely to get stuck again Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now