Sometime we need random numbers generated in javaScript for some use in our code. Let’s say we are saving 10 pictures in our images directory with names 1.jpg to 10.jpg we want to show them random then we will use javaScript to load random images.
Example of Random number in javaScript
[code lang=”js”]
<script type="text/javascript">
Math.random(); //this can generate a random number result can be 0.216487352
//this function will return result 1 to 10
Math.floor((Math.random()*10)+1);
//We can save above line in a variable and then concatinate .jpg string with it to make the image
//this function will return result 1 to 100
Math.floor((Math.random()*100)+1);
</script>
[/code]
Displaying random image from 10 images
Let’s say we have a div <div id=”image” we want to show a random image with javaScript inside that div we can use several methods but here we are using javaScript random function to show a random image this method is default built in javaScript method.
[code lang=”js”]
<script type="text/javascript">
//this function will return result 1 to 10
var image = Math.floor((Math.random()*10)+1);
document.getElementById("image").innerHTML = ‘<img src="images/’+image+’.jpg" />’; //this line will write a random image inside image id div.
</script>
[/code]