Grow your CSS skills. Land your dream job.

Generate a Random Number

Published by Chris Coyier

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.

View Demo   Download Files

 

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");
    }
    
});

Comments

  1. Thanks for the demo; nice having the code, demo and explaination on hand. One note…the demo seems to be inclusive, which i probably the intend, but the phrasing “between” usually means the min/max are excluded. I guess this can vary on one’s personal definition though. Thanks for the demo.

  2. Permalink to comment#

    As always Chris! thanks for this

  3. giesm
    Permalink to comment#

    You have a problem there :). Try (for example) to generate a random in range 7 – 15. There will be an error. Moreover: try entering range 123 – 21. It will generate a number. Your problem is: You’re comparing Strings.
    In line 31 You have (numLow <= numHigh). It should be (parseInt(numLow, 10) <= parseInt(numHigh, 10)), so that JS will compare Integers.

  4. You cant even put negative numbers

  5. Also, we’ll always have random.org…

  6. Your ‘isNumeric’ function is a little over the top! JavaScript gives us the isNaN (isNotANumber) method, so why not just wrap it like this:

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

  7. Permalink to comment#

    Overkill! Nice app though. How I pic random winners for my comments is just select a random email, name from the comments table where post equals the post id and use RAND() and LIMIT to pull one person at random using SQL

  8. Pseudo Random will be true laughs.

    But I have a question, the goal of the script is to generate an integer, isn’t it ? So why use parseFloat and not parseInt(userInput, 10) (don’t forget the base), because if we use the script you make, and we put (for instance) 2.5 for lower number and 2.75 for higher, and after generate couple of time to get random integer, you will see 3.5 some times, which is not an integer, and is out of range ;)

    Sorry for my english ;)

  9. weezer
    Permalink to comment#

    I get an error in ff 3.0.7

    Error: IsNumeric is not defined Source
    File:

    http://css-tricks.com/examples/GetRandomNumber/js/example.js

    Line: 16

  10. It’s not leaving a number for me. When I submit it just goes back to defaults.

  11. Do you really need to load the entire jQuery library? From what I can see it’s only being used for something that can be done with standard DOM JS.

  12. Eduardo
    Permalink to comment#

    I created something like this months ago and I used about 10 lines of plain javascript….
    jQuery is very cool, but in cases lke this I think it is overkill.
    Anyway, thanks for sharing you knowledge! ;)

  13. redouane
    Permalink to comment#

    Nice from you for bringing the code but we want something not random. I’m Kidding.

  14. Gustavo
    Permalink to comment#

    Cris,
    What font is that?

  15. hi ,

    This demo is great, and so useful too :)

    thank you Chris :D

    but i want to ask a question!, how can I make it work at the first clock only ?
    I mean to make it get a random number from the first click only ?

    I’m so grateful to this great job… “^^

    keep it up … and good luck .

  16. So, did I win the book?

  17. Steve
    Permalink to comment#

    The range would from 0 – 100 with the code:

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

    .random generates : 0 <= N < 1

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".