Be the first to write a review
Synchronous Randomization with JavaScript Arrays
The random number methods of Math object have been present in JavaScript for ever and have been put to good use time and time again in all manner of scenarios. One thing that the random method can easily do is display a random image on, say, your homepage. It may sound like a small thing but this randomization can be put to incredibly good use with just a little bit of planning and an easy bit of JavaScript. This one-part article will discuss the use of a multidimensional array and a basic randomization script to create a section of a page that randomly displays a series of images, complete with synchronous roll-overs, links and captions. This could be a useful addition to any site and provide a visual incentive for visitors to select products from a clearance or special offer section of your online store for example. Best of all, the code is compact, minimal and entirely client-side so if you don't have full access to server-side script languages on your web-hosts server, you can still implement it.
A lot of people, especially those new to JavaScript coding, shy away from arrays thinking them complex and unnecessary. For multidimensional arrays that fear is cubed. But arrays of any kind are the cornerstones of many of the most useful applications of JavaScript, and have featured in one way or another in most of my previous articles. In addition to a solitary text editor, you'll also need a stock of images to make the resulting page work. I've included the images that I've used in this tutorial to save you the hassle of finding and formatting images of your own. Feel free to use them in any context as they are free from copyright or royalty restrictions.
As a web developer, you'll often need to use graphics or photos in your pages. Finding a ready supply of images to satisfy your unending need used to be a real problem, but thankfully you can now use the excellent Yotophoto (http://yotophoto.com), which is the first search engine dedicated solely to allowing you to search a huge index of completely free images.
Dan Wellman
Dan Wellman is an author and web developer based in the UK. Dan has written three books so far; the latest, jQuery UI 1.7: The User Interface Library for jQuery, was released at the end of 2009.
Dan has been writing web development tutorials for over 5 years and works by day for a local digital media agency in his home town of Southampton.