Generate Random Number HTML: JS & Math.random Code

How-to basics · Updated November 23, 2026

To generate a random number in HTML, you use JavaScript’s Math.random() function inside a <script> tag or an external JS file—HTML alone has no random-number capability. For a whole number between 1 and 100, the code is Math.floor(Math.random() * 100) + 1, which you can display in a paragraph or button click.

Why HTML Needs JavaScript for Random Numbers

HTML is a markup language that defines structure and content—headings, paragraphs, images, links. It has no logic, no variables, and no functions. Every dynamic behavior, including generating a random value, must be handled by a scripting language. JavaScript is the only language browsers natively execute, so it is the standard tool for this task. When you see a “random number generator” on a webpage, the visible HTML is just the container; the actual number is produced by JavaScript code that runs in the browser.

Basic Code: Display a Random Number on Page Load

The simplest approach places the random number directly into an element when the page loads. Here is a complete, working HTML file:

<!DOCTYPE html>
<html>
<body>
<p id="result"></p>
<script>
  document.getElementById("result").textContent =
    Math.floor(Math.random() * 100) + 1;
</script>
</body>
</html>

This writes a random integer from 1 to 100 into the paragraph. The textContent property is safer than innerHTML because it treats the number as plain text, avoiding any accidental HTML parsing.

How Math.random() Actually Works

Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive). That means it can return exactly 0 but never exactly 1. The value has about 16 decimal digits of precision, like 0.4328719345710234. To turn this into a useful integer, you multiply by the range size and then round down using Math.floor().

  • 0 to 9: Math.floor(Math.random() * 10)
  • 1 to 10: Math.floor(Math.random() * 10) + 1
  • 1 to 100: Math.floor(Math.random() * 100) + 1
  • 5 to 15: Math.floor(Math.random() * 11) + 5

The general formula is Math.floor(Math.random() * (max - min + 1)) + min. The +1 inside the parentheses makes the maximum inclusive; without it, the highest value would be one less than your intended max.

Adding a Button to Generate on Demand

Most users expect to click a button to get a new number. This requires an event listener. Here is a full example with a button and a display area:

<button id="generateBtn">Generate</button>
<p id="output">Click the button</p>
<script>
  document.getElementById("generateBtn").addEventListener("click", function() {
    var randomNum = Math.floor(Math.random() * 100) + 1;
    document.getElementById("output").textContent = randomNum;
  });
</script>

The addEventListener method attaches a function that runs every time the button is clicked. You can place the button and output anywhere in your HTML body. This pattern is reusable for dice rolls, lottery picks, or quiz question shuffling.

Common Mistakes and How to Avoid Them

Several frequent errors trip up beginners:

  • Forgetting Math.floor(): Without it, you get a long decimal like 42.718293, not a whole number.
  • Off-by-one errors: Using Math.random() * 100 without +1 gives 0–99, not 1–100. Always double-check your min and max.
  • Using Math.round() instead of Math.floor(): Math.round() makes the lowest and highest values half as likely as the middle ones, creating a biased distribution. Math.floor() keeps every integer equally probable.
  • Placing script before the element: If your <script> is in the <head> and tries to access an element in the body, it fails because the element doesn’t exist yet. Put the script at the end of the body, or wrap it in window.onload.

Making It More Useful: Random Pick from a List

A common variation is picking a random item from an array, such as a name, color, or quote. The code is straightforward:

var colors = ["red", "green", "blue", "yellow", "purple"];
var randomIndex = Math.floor(Math.random() * colors.length);
var chosenColor = colors[randomIndex];

Here, colors.length (which is 5) replaces the hard-coded range, so the formula adapts automatically if you add or remove items. This technique works for any array—words, numbers, objects, or even image URLs.

Security and Fairness Considerations

Math.random() is not cryptographically secure. It is fine for games, quizzes, or visual effects, but never use it for password generation, lottery draws with real money, or security tokens. For those cases, use the Web Crypto API’s crypto.getRandomValues(), which produces cryptographically strong random values. A simple secure integer example:

var array = new Uint32Array(1);
window.crypto.getRandomValues(array);
var secureRandom = array[0] % 100 + 1;

Note that using modulo introduces a tiny bias if the range doesn’t evenly divide 2^32, but for most non-critical uses it’s acceptable. If you need true fairness for something like a raffle, consider a rejection sampling method, though that’s rarely necessary for basic web pages.

Frequently Asked Questions

Can I generate a random number without JavaScript?

No. HTML alone cannot compute anything. You need JavaScript, or a server-side language like PHP or Python that generates the number before the page loads. If you must avoid JavaScript, you could use a server-side script, but then the number is fixed until the page reloads.

How do I set a minimum and maximum?

Use the formula Math.floor(Math.random() * (max - min + 1)) + min. For example, for 50 to 100, replace min with 50 and max with 100: Math.floor(Math.random() * 51) + 50. The +1 ensures 100 is possible.

Why do I get the same number every time I refresh?

You shouldn’t, unless your code is outside a function and the page is cached. Browsers do cache pages, but Math.random() is re-evaluated each load. If you see the same number, check that your script actually runs—look for console errors in the browser’s developer tools (F12).

Is Math.random() truly random?

No, it’s a pseudo-random number generator (PRNG). It uses a deterministic algorithm seeded by the browser. The sequence looks random but is reproducible if you know the seed. For most web purposes, this is fine. For gambling or security, use crypto.getRandomValues().

Can I generate a random decimal between 0 and 1?

Yes, that’s exactly what Math.random() returns by default. If you need a decimal between 0 and 10, multiply: Math.random() * 10. To get two decimal places, use Math.round(Math.random() * 100) / 100.

How do I show the number in an input field instead of a paragraph?

Set the value property instead of textContent. For an input with id numInput, use document.getElementById("numInput").value = randomNum;. This works for text inputs; for number inputs, the value is still a string but the browser validates it.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.