JavaScript - randomize

revision:


Content

Math.random() method Proper random functions Some practical examples The rolling dice game Random color generator Choose a random number Choose a random image Randomize and timing Random image generator using JavaScript Using JavaScript to run a function every 3 seconds


Math.random() method

top

The Math.random() static method returns a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.

The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Syntax: Math.random();

Return value: a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

examples
code:
                    <div class="spec">
                        <div id="random1"></div>
                        <div id="random2"></div>
                        <div id="random3"></div>
                        <div id="random4"></div>
                        <div id="random5"></div>
                        <div id="random6"></div>
                    </div>
                    <script>
                        function getRandomInt(max) {
                            return Math.floor(Math.random() * max);
                        }
                        document.getElementById('random1').innerHTML = "result: " + getRandomInt(3);   // Expected output: 0, 1 or 2
                        document.getElementById('random2').innerHTML = "result: " + getRandomInt(1);  // Expected output: 0
                        document.getElementById('random3').innerHTML = "result: " + getRandomInt();  // Expected output: 0
                        // getting a random integer
                        function getRandom(min, max){
                            min = Math.ceil(min);
                            max = Math.floor(max);
                            return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
                        
                        } 
                        document.getElementById('random4').innerText = "the result is: " + getRandom(1, 4);
                        // getting a random integer between two values, inclusive
                        function getRandomIntInclusive(min, max) {
                            min = Math.ceil(min);
                            max = Math.floor(max);
                            return Math.floor(Math.random() * (max - min + 1) + min); // The maximum is inclusive and the minimum is inclusive
                        }
                        document.getElementById("random5").textContent = "the random number is : " + getRandomIntInclusive(3, 9); 
                                    
                    </script>
                


Proper random functions

top
examples

The JavaScript functions here below always returns a random number between min (included) and max (excluded).


code:
                    <div>
                        <div><button onclick="document.getElementById('random7').innerHTML = getRndInteger(0,10)">click me:</button>
                        <span class="spec" id="random7"></span></div><br>
                        <div class="spec" id="random8"></div>
                        <div class="spec" id="random9"></div>
                        <div class="spec" id="random10"></div>
                        
                    </div>
                    <script>
                        function getRndInteger(min, max) {
                            return Math.floor(Math.random() * (max - min)) + min;
                        }                
        
                        const lowest = 1;
                        const highest = 10;
                        let randomNumber = Math.random() * (highest - lowest) + lowest;
                        document.getElementById('random8').innerHTML = randomNumber;
        
                        const low = 1;
                        const high = 10;
                        let rndNumber = Math.random() * (high - low) + low;
                        number = Math.floor(rndNumber);
                        document.getElementById("random9").innerHTML = number;
                    </script>
                

examples

The JavaScript functions here below always returns a random number between min and max (bot included).



code:
                        <div>
                            <div><button onclick="document.getElementById('random11').innerHTML = getRndInteger_1(1,10)">click me too</button><
                            span class="spec" id="random11"></span><br><br>
                            <div class="spec" id="random12"></div>
                            <div class="spec" id="random13"></div>
                            <div class="spec" id="random14"></div>
                        </div>
                        <script>
                            function getRndInteger_1(min, max) {
                                return Math.floor(Math.random() * (max - min + 1) ) + min;
                            }
                            const getRandomNumber = (min, max) => {
                                return Math.floor(Math.random() * (max - min + 1)) + min;
                            };
                            document.getElementById('random12').innerHTML = "the result is : " + getRandomNumber(4, 8);
                        
                        </script>
                    



Some practical examples

top
examples

press the button for number 0 to 9 to look for random number.

press the button for number to look for a random number between 1 and 10.

p>press the button for generating a random number.

press the button for generating a random number.

code:
                    <div>
                        <p>press the button for number 0 to 9 to look for random number.</p>
                        <div><button onclick="a_functn()">run</button><span class="spec" id="demo-1"></span></div>
                        <p>press the button for number to look for a random number between 1 and 10.</p>
                        <div><button onclick="k_functn()">run</button><span class="spec" id="demo-2"></span></div>
                        p>press the button for generating a random number.</p>
                        <div><button onclick="m_functn()">click</button><span class="spec" id="demo-3"></span>
                        <p>press the button for generating a random number.</p>
                        <div><button onclick="o_functn()">click</button><span class="spec" id="demo-4"></span></div>
                    </div>
                    <script>
                        function a_functn() {
                            var z_i = Math.floor((Math.random() /9) + 3);
                            document.getElementById("demo-1").innerHTML = z_i;
                        }
            
                        function k_functn() {
                            var y_u = Math.floor((Math.random() * 12) - 6);
                            document.getElementById("demo-2").innerHTML = y_u
                        }
            
                        function m_functn() {
                            var zo_1 = Math.floor((Math.random() * 100) + 6);
                            document.getElementById("demo-3").innerHTML = zo_1
                        }
            
                        function o_functn() {
                            var ho_1 = Math.floor((Math.random() * 50) + 3);
                            document.getElementById("demo-4").innerHTML = ho_1
                        }
                    </script>

                


The rolling dice game

top
example
code:
                    <div id="app">
                        <div>
                            <input id="player1" placeholder="Enter player 1 name" />
                        </div>
                        <div>
                            <input id="player2" placeholder="Enter player 2 name" />
                        </div>
                        <button id="roll">Roll Dice</button>
                        <div id="results"></div>
                    </div>
                    <style>
            
                    </style>
                    <script>
                        const getRandomNumbers = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
                        const rollDice = () => getRandomNumbers(1, 6);
                        document.getElementById("roll").addEventListener("click", function () {
                            // fetch player names from the input fields
                            const player1 = document.getElementById("player1").value;
                            const player2 = document.getElementById("player2").value;
            
                            // roll dice for both players
                            const player1Score = rollDice();
                            const player2Score = rollDice();
            
                            // initialize empty string to store result
                            let result = "";
            
                            // determine the result
                            if (player1Score > player2Score) {
                                result = `${player1} won the round`;
                            } else if (player2Score > player1Score) {
                                result = `${player2} won the round`;
                            } else {
                                result = "This round is tied";
                            }
            
                            // display the result on the page
                            document.getElementById("results").innerHTML = `
                            <p>${player1} => ${player1Score}</p>
                            <p>${player2} => ${player2Score}</p>
                            <p>${result}</p>
                            `;
                        });
                    </script>
                


Random color generator

top
examples

#000000

click to change the color

code:
                    <div>
                        <div id="color1">
                            <div>
                                <input type="color" id="color">
                                <h4 id="text">#000000</h4>
                                <p>click to change the color</p>
                            </div>
                        </div>
                    </div>
                    <style>
                        #color{width: 30vw; height: 5vw; border: 0.2vw solid burlywood}
                        h4, h5, p{ font-family: sans-serif; text-align: center; }
                        #color1{ width: 100%; height: 10vh; display: flex; align-items: center; justify-content: center;}
                    </style>
                    <script>
                        function randomInteger(max){
                            return Math.floor(Math.random()*(max + 1));
                        }
                        function randomRgbColor() {
                            let r = randomInteger(255);
                            let g = randomInteger(255);
                            let b = randomInteger(255);
                            return [r,g,b];
                        }
            
                        function randomHexColor() {
                            let [r,g,b] =randomRgbColor();
                            let hr = r.toString(16).padStart(2, '0');
                            let hg = g.toString(16).padStart(2, '0');
                            let hb = b.toString(16).padStart(2, '0');
                            return "#" + hr + hg + hb;
                        }
            
                        function changeColor() {
                            let hex = randomHexColor();
                            document.getElementById('color').value = hex;
                            document.getElementById('text').innerHTML = hex;
                        }
            
                        function clickHandler(event) {
                            changeColor();
                            event.preventDefault();
                        }
                        document.getElementById("color1").addEventListener('click', clickHandler);
                        changeColor();            
            
                    </script>
                


Choose a random number

top
examples
code:
                    <div>
                        <div id="number"></div>
                    </div>
                    <style>
            
                    </style>
                    <script>
                        const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];
                        const chooseRandom = (arr, num = 1) => {
                            const res = [];
                            for(let i = 0; i < num; ){
                                const random = Math.floor(Math.random() * arr.length);
                                if(res.indexOf(arr[random]) !== -1){
                                    continue;
                                };
                                res.push(arr[random]);
                                i++;
                            };
                            return res;
                        
                            };
                        document.getElementById('number').innerHTML = chooseRandom(arr, 4);
                    </script>

                


Choose a random image

top
examples
code:
                    <div>
                        <div>
                            <button id="jsstyle" onclick="display_random_image();">show image</button> 
                        </div>
                        <div id="box"></div>
                    </div>
                    <script>
                        function display_random_image() {
                            var theImages = [
                                {src:"../../pics/1.jpg", width:"500", height:"400"}, 
                                {src:"../../pics/2.jpg", width:"500", height:"400"},
                                {src:"../../pics/3.jpg", width:"500", height:"400"},
                                {src:"../../pics/4.jpg", width:"500", height:"400"},
                                {src:"../../pics/5.jpg", width:"500", height:"400"},
                                {src:"../../pics/6.jpg", width:"500", height:"400"}];
                            var preBuffer = [];
                            for (var i = 0, j = theImages.length; i < j; i++) {
                                preBuffer[i] = new Image();
                                preBuffer[i].src = theImages[i].src;
                                preBuffer[i].width = theImages[i].width;
                                preBuffer[i].height = theImages[i].height;
                            }
                            // create random image number
                            function getRandomInt(min,max) {
                                imn = Math.floor(Math.random() * (max - min + 1)) + min;
                                return preBuffer[imn];
                                }  
                            // 0 is first image,   preBuffer.length - 1) is  last image
                            var newImage = getRandomInt(0, preBuffer.length - 1);
                            // remove the previous images
                            var images = document.getElementsByTagName('img');
                            var l = images.length;
                            for (var p = 0; p < l; p++) {
                                images[0].parentNode.removeChild(images[0]);
                            }
                            // display the image  
                            box.appendChild(newImage);
                        }
                    </script>
                


Randomize and timing

top
examples

show random pictures

code:
                    <div>
                        <p class="spec">show random pictures</p>
                        <div class="spec" id="demo"></div>
                    </div>
                    <script>
                        var myVar = setInterval(display, 1000);
                        function display() {
                            var myImages = [
                                {src:"../../pics/1.jpg", width:"500", height:"400"}, 
                                {src:"../../pics/2.jpg", width:"500", height:"400"},
                                {src:"../../pics/3.jpg", width:"500", height:"400"},
                                {src:"../../pics/4.jpg", width:"500", height:"400"},
                                {src:"../../pics/5.jpg", width:"500", height:"400"},
                                {src:"../../pics/6.jpg", width:"500", height:"400"}];
                            var preBuffer = [];
                            for (var i = 0, j = myImages.length; i < j; i++) {
                                preBuffer[i] = new Image();
                                preBuffer[i].src = myImages[i].src;
                                preBuffer[i].width = myImages[i].width;
                                preBuffer[i].height = myImages[i].height;
                                }
                            // create random image number
                            function getRandomInt(min,max) {
                                imn = Math.floor(Math.random() * (max - min + 1)) + min;
                                return preBuffer[imn];
                                }  
                            // 0 is first image,   preBuffer.length - 1) is  last image
                            var newImage = getRandomInt(0, preBuffer.length - 1);
                            // remove the previous images
                            var images = document.getElementsByTagName('img');
                            var l = images.length;
                            for (var p = 0; p < l; p++) {
                                images[0].parentNode.removeChild(images[0]);
                            }
                            demo.appendChild(newImage);
                        }
                    
                    </script>
                


Random image generator using JavaScript

top

Approach: the pictures which are going to be generated randomly on the website should be stored in the form of an array. These pictures will be displayed to the user within a regular time interval.The setInterval() function is used to set a timer between the images to display and the floor(Math.random()*pics.length) method will generate a random number between 0 and the length of the array that is assigned to the images to display randomly.

Step 1: in the HTML page, create an empty section that will contain the randomly generated pictures.

Step 2: In JavaScript, create an array of image links. The images inside the array are to be generated randomly on the webpage. We will call the indexes of this array randomly using Math.random function to be displayed.

Step 2: creeate a JavaScript variable to store a random value calculated by using the Math library, i.e. Math.floor(Math.random()*pics.length). This will generate a random number between 0 and the length of the pics array and thsi number will be assigned to the images inside the pics array to display them randomly.

The result
code:
                    <div>
                        <div class="container">
                            <section></section>
                        </div>
                    </div>
                    <style>
                        .container {margin: 1.5vh 2vw; margin-top: 5vh; text-align: center; background: rgb(39, 188, 209); 
                            background: linear-gradient(118deg, rgba(39, 188, 209, 0.9783263647255778) 0%, rgba(6, 14, 101, 1) 100%); 
                            opacity: 0.9;color: white; padding: 1vw 1vw; border-radius: 20px; min-height: 15vh;}
                        section { height: 70vh; width: 100%; margin-top: 0.5vw; background-position: center; background-repeat: no-repeat;}
                    </style>
                    <script>
                        const pics = ["url('../../pics/1.jpg')","url('../../pics/2.jpg')","url('../../pics/3.jpg')","url('../../pics/4.jpg')","url('../../pics/5.jpg')","url('../../pics/6.jpg')","url('../../pics/7.jpg')"];
                        const pic = document.querySelector('section');
                        function showImage() {
                            var a = Math.floor(Math.random() * pics.length);
                            var img = pics[a];
                            pic.style.backgroundImage = img;
                        }
                        setInterval(showImage, 1000);
                    </script>
                


Using JavaScript to run a function every 3 seconds

top
examples
Change color every 3 seconds
Stop background color change
code:
                    <style>
                        #div2 {margin-left: 1vw;width:30vw; height: 20vw; background: #7bbfa2; }
                        .click-me{margin-left:1vw; width: 20vw;background-color:lightblue;color:black;border:0.1vw solid burlywood;cursor:pointer; 
                            padding: 1vw; border-radius: 45%;text-align:center;}
                    </style>
                    <div id="div1">
                        <div id="div2"></div>
                        <div id="click-me1" class="click-me" onclick="startBackground()">Change color every 3 seconds</div>
                        <div id="click-me2" class="click-me" onclick="stopBackground()">Stop background color change</div>
                    </div>
                    <script>
                        var isSetTimmeoutRunning = false;
                        var interval;
                        function startBackground(){
                            isSetTimmeoutRunning = true;
                            interval = setInterval(function(){
                                var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
                                document.getElementById("div2").style.backgroundColor = randomColor;
                            }, 3000);
                        }
                        function stopBackground(){
                            clearInterval(interval);
                            isSetTimmeoutRunning = false;
                        }
                    </script>