The steps involved in randomly displaying an image from a set are very similar to those used for displaying random text strings.
var img_name = new Array("purple.gif", "red.gif", "blue.gif", "yellow.gif", "green.gif", "pink.gif"); var l = img_name.length; var rnd_no = Math.floor(l*Math.random()); document.r_img.src = img_name[rnd_no]; <img src="purple.gif" width="100" height="50" name="r_img" alt="Random image" />
Note: Array are zero-indexed, so the last element in the array will the length of the array minus 1. However, since we are employing floor() to get an integer, we can use the value from ARRAY_NAME.length directly.
You can also use the id attribute of the image tag instead of name; as:
var img_name = new Array("purple.gif", "red.gif", "blue.gif", "yellow.gif", "green.gif", "pink.gif"); var l = img_name.length; var rnd_no = Math.floor(l*Math.random()); document.getElementById("randomimage").src = img_name[rnd_no]; <img src="purple.gif" width="100" height="50" id="randomimage" alt="Random image" />
A potential use of the random image displaying code is when you want to show a single banner from a set – though I would prefer using server-side scripts like PHP or Perl for this. I have also employed the code to randomly rotate images at a designated place on the web page.
Starting 2011, Google agreed to pay Mozilla Corporation a tad less than half a billion dollars over a period of 3 years if they kept Google as the default search engine on their Firefox web browser. This was a very smart move from the company. Because in 2008, Google had launched Chrome, their own web browser, which had the world's most popular search engine as the default. Additionally, by the end of 2011, Chrome's usage surpassed that of Firefox, and by early 2012, it had exceeded that of Internet Explorer. It was now the world's most popular web browser. So, even though some might think that Google spent a gargantuan sum of money needlessly, I admire the think-tanks at the company. They kept pushing the usage of their core product, the one that made them the most valuable web company - the Google search engine. By the way, in 2006, Google had dished out $57 million to have their search bar in the Firefox. This amounted to 85% of Mozilla Corporation's total revenue. [more...]