[JavaSript]Generating Random Numbers in JavaScript and Applying Them to CSS Variables

目次

Overview

JavaScript uses the Math.random() method for irregular processes such as rolling dice or creating random background colors. This method only generates a decimal between 0 and 1. However, by combining it with Math.floor(), integers within a specific range (e.g., 1–100) can be created. This article introduces basic random number generation logic and an implementation that randomly changes element gradient colors upon clicking.

Specifications (Input/Output)

Input: User button click.

Output: Generation of a random integer between 0 and 360 for hue. Application of the generated value to CSS variables to change the color of a rectangle on the screen.

Basic Usage

The following table shows the basic formulas for processing Math.random().

GoalCodeExample Result
Decimal between 0 and 1Math.random()0.123…, 0.987…
Integer between 0 and 99Math.floor(Math.random() * 100)0, 55, 99
Integer between 10 and 1910 + Math.floor(Math.random() * 10)10, 15, 19

Full Code (HTML / JavaScript)

HTML (index.html)

A rectangle for display and a button to trigger the change are placed. CSS variables --hue-start and --hue-end control the gradient colors.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Color Generator</title>
    <style>
        body {
            font-family: sans-serif;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }
        
        .color-box {
            width: 300px;
            height: 200px;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            
            --hue-start: 0;
            --hue-end: 40;
            
            background: linear-gradient(
                135deg, 
                hsl(var(--hue-start), 100%, 60%), 
                hsl(var(--hue-end), 100%, 50%)
            );
            
            transition: background 0.5s ease;
        }

        .trigger-button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #333;
            color: #fff;
            border: none;
            border-radius: 4px;
        }
        
        .trigger-button:hover {
            background-color: #555;
        }
    </style>
    <script src="random-color.js" defer></script>
</head>
<body>
    <div class="color-box" id="target-rectangle"></div>
    <button class="trigger-button" id="change-btn">Change Color</button>
</body>
</html>

JavaScript (random-color.js)

A random hue between 0 and 360 is generated upon clicking the button to rewrite the CSS variables of the DOM element.

/**
 * Utility function to generate a random integer within a specified range
 * @param {number} max - Maximum value (exclusive)
 * @returns {number} Integer from 0 to max - 1
 */
const getRandomInt = (max) => {
    // Math.random() : random decimal between 0 and 1
    // Math.floor()  : rounds down to the nearest integer
    return Math.floor(Math.random() * max);
};

/**
 * Color change event handler
 */
const updateBoxColor = () => {
    const rectangle = document.querySelector("#target-rectangle");
    
    const randomHue = getRandomInt(360);
    
    const startHueVal = randomHue;
    const endHueVal = randomHue + 40;

    rectangle.style.setProperty("--hue-start", startHueVal);
    rectangle.style.setProperty("--hue-end", endHueVal);
    
    console.log(`New hue: ${startHueVal} -> ${endHueVal}`);
};

const button = document.querySelector("#change-btn");
if (button) {
    button.addEventListener("click", updateBoxColor);
}

Customization Points

Using the formula Math.floor(Math.random() * (max - min) + min) allows for random number generation within any specified range, such as between 100 and 200. While saturation and lightness are fixed in this example, randomizing these values can also represent various tones such as pastels or dark colors.

Important Points

Math.random() uses a predictable algorithm. Do not use this method for values that must not be predicted, such as password generation or security tokens. In those cases, use crypto.getRandomValues(). Additionally, using Math.floor() is standard for integer generation because Math.round() results in a lower probability for the minimum and maximum values.

Advanced Usage

Random Extraction from an Array

Using the generated random number as an array index allows for picking one item randomly from a list.

const fortunes = ["Great Blessing", "Middle Blessing", "Small Blessing", "Curse"];
const randomIndex = Math.floor(Math.random() * fortunes.length);
console.log(`Today's Fortune: ${fortunes[randomIndex]}`);

Summary

The Math.random() method is a simple tool that returns a decimal between 0 and 1, but it offers many possibilities when combined with multiplication and rounding. This technique is essential for adding dynamic changes to user interfaces or creating game mechanics. Mastering the conversion formula for integer ranges is highly recommended.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次