Generate a Random Number

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

For the last two book giveaways I did, I promised I would pick a winner totally at random from the comments. There were hundreds of comments, so I wasn’t about to write the numbers on little bits of paper and pick them from a hat. I actually have a dice-rolling iPhone app I was going to use, but then I figured what the heck I might as well build a little webpage to do it quick.

I moved the demo of this post to this CodePen, which is far more practical, although a smidge old-school with the jQuery and all. The rest of the post I’ll leave largely intact.

Here’s a version without jQuery…

JavaScript Random Number

Generating a random number with JavaScript is pretty trivially easy:

var numRand = Math.floor(Math.random() * 101);

That will return a random number between 1-100. But wanted to make this website a bit more useful, in that it will take a low and high value and return a random number between those two values.

HTML

A couple of text inputs, a “Generate!” button, and an empty div container to stick the number will do:

<input type="text" id="lownumber" value="1" />
and
<input type="text" id="highnumber" value="100" />

<br />

<input type="submit" id="getit" value="Generate!" />

<div id="randomnumber"></div>

jQuery

When the “Generate!” button is clicked, we’ll do the work:

$("#getit").click(function() {
    
        var numLow = $("#lownumber").val();
        var numHigh = $("#highnumber").val();
        
        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
        
        var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
        
        if ((IsNumeric(numLow)) && (IsNumeric(numHigh)) && (parseFloat(numLow) <= parseFloat(numHigh) && (numLow != '') && (numHigh != '')) {
            $("#randomnumber").text(numRand);
        } else {
            $("#randomnumber").text("Careful now...");
        }
        
        return false;
});

The easiest way I thought of was to subtract the low from the high, generate a random number between 1 and that, and then add the low back in. To ensure that worked, we need to check a variety of things:

  • The inputs aren’t blank and are numbers
  • The first number is lower than the second

I used this classic IsNumeric function to check if they were actually numbers: Updated IsNumeric function (10 times easier) thanks to James:

function isNumeric(n){
  return !isNaN(n);
}

As a final touch, I wanted to have the default numbers 1 and 100 in there, but have them easy to change. So as soon as you tab to or click either element, it clears the number and changes the color to black. It also ensures that if you tab or click there AGAIN, it WON’T do that.

$("input[type=text]").each(function(){
    $(this).data("first-click", true);
});

$("input[type=text]").focus(function(){
   
    if ($(this).data("first-click")) {
        $(this).val("");
        $(this).data("first-click", false);
        $(this).css("color", "black");
    }
    
});