Random Number Picker In Vanilla JavaScript

Category: Javascript | April 8, 2021
Author:devchazz
Views Total:901 views
Official Page:Go to website
Last Update:April 8, 2021
License:MIT

Preview:

Random Number Picker In Vanilla JavaScript

Description:

A Vanilla JS powered random number picker that allows you to generate a random number within a specified range.

How to use it:

1. Create min/max input fields.

<input type="number" class="input-number" id="minValue" />
<input type="number" class="input-number" id="maxValue" />

2. Create a button to generate a random number.

<input type="submit" id="btn" onclick="pick()" value="Generate" />

3. Create a container to hold the result.

<p id="result">Result</p>

4. The core JavaScript to enable the random number picker.

function pick() {
    var result = document.getElementById("result")
    var min = document.getElementById("minValue").value
    var max = document.getElementById("maxValue").value
    if (min && max) {
        if (min > max) {
            let n3 = min
            let n4 = max
            max = n3
            min = n4
        }
        min = Math.ceil(min)
        max = Math.ceil(max) + 1
        resultFinal = Math.floor(Math.random() * (max - min)) + min
        result.innerHTML = resultFinal
    }
}

You Might Be Interested In:


Leave a Reply