How to Generate Random Number in HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to generate random numbers using HTML, CSS, and JavaScript. This step-by-step guide shows you how to create a random number generator with modern UI.


how-to-generate-random-number-in-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Generating random numbers is an important task in web development, especially for games, quizzes, or apps. With HTML, CSS, and JavaScript, you can create a simple yet attractive random number generator. In this tutorial, we'll show you how to make one with a modern and interactive UI.

Before we start, let's check what you need to know.

Prerequisites:

  • Basic understanding of HTML: For creating the structure of the web page.
  • Basic understanding of CSS: To style the page and make it look good.
  • Basic knowledge of JavaScript: To add functionality to the random number generator.

Source Code

Step 1 (HTML Code):

First, we’ll create the basic structure of the page using HTML. We need a heading, a section to display the random number, and a button to generate it. Let’s break it down step by step:

1. <!DOCTYPE html>:

  • This declares the document type as HTML5, ensuring the browser knows how to render the page.

2. <html lang="en">:

  • This is the opening tag for the HTML document. The lang="en" specifies that the language of the page is English.

3. <head>:

  • This section contains metadata and links to external resources.

    Inside the head tag:

    • <meta charset="UTF-8">: This defines the character encoding for the document, making sure characters are properly displayed.
    • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive, adapting to different screen sizes (especially important for mobile).
    • <title>Random Number Generator</title>: This sets the title of the webpage, which appears in the browser tab.
    • <link rel="stylesheet" href="styles.css">: This links to an external CSS file (styles.css) to style the page.
    • <link href="https://fonts.google....t; rel="stylesheet">: This imports the Poppins font from Google Fonts, used to style the text on the page.

4. <body>:

  • This section contains the visible content of the webpage.

    Inside the body tag:

    • <div class="container">: A container div that holds all the main content for the random number generator.

      Inside the container:

      • <h1>Random Number Generator</h1>: A header for the page that displays the title "Random Number Generator."
      • <div class="input-range">: A div that holds input fields for setting the range for the random number.

        Inside this div:

        • <label for="min">Min: </label>: A label for the minimum number input.
        • <input type="number" id="min" placeholder="1" value="1">: An input field to specify the minimum number, defaulting to 1.
        • <label for="max">Max: </label>: A label for the maximum number input.
        • <input type="number" id="max" placeholder="100" value="100">: An input field to specify the maximum number, defaulting to 100.
      • <div class="random-number" id="randomNumber">0</div>: A div that displays the generated random number, starting with 0 as the default value.
      • <button id="generateButton">Generate Random Number</button>: A button that triggers the generation of a random number.
      • <button id="copyButton">Copy to Clipboard</button>: A button that copies the generated number to the clipboard.

5. <script src="script.js"></script>:

  • This links to an external JavaScript file (script.js) that contains the logic for generating random numbers and copying them to the clipboard

Step 2 (CSS Code):

Next, we’ll add some CSS to make the interface look clean and modern. Let’s break down the CSS code:

1. Universal Selector (*)

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
  • *: This applies to all elements on the page.
    • margin: 0: Removes default margins from all elements.
    • padding: 0: Removes default padding from all elements.
    • box-sizing: border-box: Ensures that padding and border are included in the element's width and height, making layout calculations easier.

2. body

body {
  font-family: 'Poppins', sans-serif;
  background: linear-gradient(135deg, #74ebd5 0%, #ACB6E5 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
  • font-family: Uses the 'Poppins' font imported from Google Fonts, with sans-serif as a fallback.
  • background: Applies a diagonal gradient from #74ebd5 to #ACB6E5, creating a visually appealing background.
  • display: flex: Makes the body a flex container, which helps align its contents.
  • justify-content: center and align-items: center: Centers the content both horizontally and vertically.
  • height: 100vh: Makes the body height 100% of the viewport height, ensuring full-screen centering.

3. .container

.container {
  background-color: white;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  text-align: center;
  width: 350px;
}
  • background-color: Sets the container background to white.
  • padding: 40px: Adds space inside the container.
  • border-radius: 15px: Rounds the corners of the container for a modern look.
  • box-shadow: Adds a shadow to the container to create depth (e.g., makes it look elevated).
  • text-align: center: Centers text within the container.
  • width: 350px: Sets the container's width to 350 pixels.

4. h1

h1 {
  margin-bottom: 20px;
  font-size: 26px;
  font-weight: 600;
  color: #333;
}
  • margin-bottom: 20px: Adds space below the header.
  • font-size: 26px: Sets the font size to 26px.
  • font-weight: 600: Makes the text semi-bold.
  • color: #333: Applies a dark gray color to the text.

5. .input-range

.input-range {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}
  • display: flex: Makes this div a flex container, aligning its children (label and input) in a row.
  • justify-content: center: Centers the input and labels horizontally.
  • gap: 10px: Adds 10px of space between the inputs and labels.
  • margin-bottom: 20px: Adds space below this section.

6. .input-range label

.input-range label {
  font-size: 16px;
  font-weight: 500;
  color: #555;
}
  • font-size: 16px: Sets the font size to 16px.
  • font-weight: 500: Makes the label text slightly bold.
  • color: #555: Gives the labels a medium gray color.

7. .input-range input

.input-range input {
  width: 60px;
  padding: 8px;
  border-radius: 5px;
  border: 1px solid #ccc;
  font-size: 16px;
  text-align: center;
}
  • width: 60px: Sets the width of the input fields to 60px.
  • padding: 8px: Adds internal padding to the input fields.
  • border-radius: 5px: Rounds the input field corners slightly.
  • border: 1px solid #ccc: Adds a light gray border around the input.
  • font-size: 16px: Sets the font size inside the input field.
  • text-align: center: Centers the text within the input field.

8. .random-number

.random-number {
  font-size: 50px;
  color: #007bff;
  margin-bottom: 20px;
  font-weight: 600;
  transition: transform 0.3s ease;
}
  • font-size: 50px: Sets the size of the displayed random number.
  • color: #007bff: Applies a blue color to the number.
  • margin-bottom: 20px: Adds space below the random number display.
  • font-weight: 600: Makes the number bold.
  • transition: transform 0.3s ease: Adds a smooth animation effect when the number is transformed (e.g., when changed or updated).

9. button

button {
  background-color: #007bff;
  color: white;
  padding: 12px 25px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 18px;
  margin: 10px 0;
  transition: background-color 0.3s ease, transform 0.3s ease;
}
  • background-color: #007bff: Makes the button blue.
  • color: white: Sets the text color to white.
  • padding: 12px 25px: Adds internal spacing to the button.
  • border: none: Removes any default border.
  • border-radius: 10px: Rounds the button corners.
  • cursor: pointer: Changes the cursor to a pointer when hovering over the button.
  • font-size: 18px: Sets the button text size to 18px.
  • margin: 10px 0: Adds vertical spacing around the button.
  • transition: background-color 0.3s ease, transform 0.3s ease: Smoothly transitions both the background color and size changes when hovering.

10. button:hover

button:hover {
  background-color: #0056b3;
  transform: scale(1.05);
}
  • background-color: #0056b3: Changes the background to a darker blue when the user hovers over the button.
  • transform: scale(1.05): Slightly increases the button size when hovered to create a hover effect.

11. #copyButton

#copyButton {
  background-color: #28a745;
}

#copyButton:hover {
  background-color: #218838;
}
  • #copyButton: The copy button has a different background color (green: #28a745).
  • #copyButton:hover: When hovering, the background changes to a darker green.

12. Media Query for Small Screens (@media)

@media (max-width: 400px) {
  .container {
    width: 100%;
    padding: 20px;
  }

  .random-number {
    font-size: 40px;
  }

  button {
    font-size: 16px;
  }
}
  • @media (max-width: 400px): This is a media query for screens with a maximum width of 400px (small devices).

    Inside this media query:

    • The container width is set to 100% and the padding is reduced.
    • The random number's font size is reduced to 40px.
    • The button text size is reduced to 16px.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Poppins', sans-serif;
  background: linear-gradient(135deg, #74ebd5 0%, #ACB6E5 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: white;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  text-align: center;
  width: 350px;
}

h1 {
  margin-bottom: 20px;
  font-size: 26px;
  font-weight: 600;
  color: #333;
}

.input-range {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.input-range label {
  font-size: 16px;
  font-weight: 500;
  color: #555;
}

.input-range input {
  width: 60px;
  padding: 8px;
  border-radius: 5px;
  border: 1px solid #ccc;
  font-size: 16px;
  text-align: center;
}

.random-number {
  font-size: 50px;
  color: #007bff;
  margin-bottom: 20px;
  font-weight: 600;
  transition: transform 0.3s ease;
}

button {
  background-color: #007bff;
  color: white;
  padding: 12px 25px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 18px;
  margin: 10px 0;
  transition: background-color 0.3s ease, transform 0.3s ease;
}

button:hover {
  background-color: #0056b3;
  transform: scale(1.05);
}

#copyButton {
  background-color: #28a745;
}

#copyButton:hover {
  background-color: #218838;
}

@media (max-width: 400px) {
  .container {
    width: 100%;
    padding: 20px;
  }

  .random-number {
    font-size: 40px;
  }

  button {
    font-size: 16px;
  }
} 

Step 3 (JavaScript Code):

Finally, we’ll add JavaScript to make the random number generation work. Here's a detailed breakdown of how it works:

1. Event Listener for the 'Generate' Button

document.getElementById('generateButton').addEventListener('click', function() {
  const min = parseInt(document.getElementById('min').value) || 1;
  const max = parseInt(document.getElementById('max').value) || 100;

  const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

  const numberDisplay = document.getElementById('randomNumber');
  numberDisplay.innerText = randomNumber;

  numberDisplay.style.transform = 'scale(1.2)';
  setTimeout(() => {
    numberDisplay.style.transform = 'scale(1)';
  }, 300);
});

Step-by-Step Explanation:

  1. Button Click Event:
    • The code listens for a click event on the element with the ID generateButton. When the button is clicked, it runs the attached function.
  2. Getting Min and Max Values:
    • min and max are extracted from the input fields with IDs min and max. If no value is provided, default values of 1 for min and 100 for max are used (due to || 1 and || 100).
    • parseInt() is used to convert the string values from the input fields into integers.
  3. Generating a Random Number:
    • A random number is generated between the specified min and max range using this formula:
      Math.floor(Math.random() * (max - min + 1)) + min;
    • Math.random() generates a decimal between 0 and 1.
    • Math.random() * (max - min + 1) scales this to the desired range.
    • Math.floor() rounds the number down to the nearest integer.
    • Finally, + min shifts the range to start at min.
  4. Displaying the Random Number:
    • The randomly generated number is displayed by setting the innerText of the element with the ID randomNumber to the generated number.
  5. Number Scaling Animation:
    • The number is temporarily scaled up by applying a scale(1.2) transform, which makes the number appear larger.
    • After 300 milliseconds (using setTimeout), the scale is reset to 1, making the number return to its original size. This gives a simple "bounce" effect when a new number is generated.

2. Event Listener for the 'Copy' Button

document.getElementById('copyButton').addEventListener('click', function() {
  const randomNumber = document.getElementById('randomNumber').innerText;
  
  // Create a temporary input element to copy the number
  const tempInput = document.createElement('input');
  document.body.appendChild(tempInput);
  tempInput.value = randomNumber;
  tempInput.select();
  document.execCommand('copy');
  document.body.removeChild(tempInput);

  // Change button text temporarily
  const copyButton = document.getElementById('copyButton');
  copyButton.innerText = 'Copied!';
  setTimeout(() => {
    copyButton.innerText = 'Copy to Clipboard';
  }, 2000);
});

Step-by-Step Explanation:

  1. Button Click Event:
    • This code listens for a click event on the element with the ID copyButton. When the button is clicked, it executes the function.
  2. Get the Random Number:
    • The current random number (from the previous generation) is obtained from the innerText of the element with ID randomNumber.
  3. Copy the Number to the Clipboard:
    • A temporary input element is created using document.createElement('input').
    • This temporary input is added to the DOM (document body) using appendChild().
    • The random number is assigned to the value of the input element.
    • The select() method is used to highlight the text inside the input field, and then document.execCommand('copy') copies the selected text to the clipboard.
    • The temporary input element is removed from the DOM using removeChild() after copying the number.
  4. Change Button Text:
    • Once the number is copied, the text of the button (copyButton) is temporarily changed to "Copied!" to give feedback to the user.
    • After 2 seconds (2000 milliseconds), the button text is reset to "Copy to Clipboard" using setTimeout().
document.getElementById('generateButton').addEventListener('click', function() {
  const min = parseInt(document.getElementById('min').value) || 1;
  const max = parseInt(document.getElementById('max').value) || 100;
  
  const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;

  const numberDisplay = document.getElementById('randomNumber');
  numberDisplay.innerText = randomNumber;

  numberDisplay.style.transform = 'scale(1.2)';
  setTimeout(() => {
    numberDisplay.style.transform = 'scale(1)';
  }, 300);
});

document.getElementById('copyButton').addEventListener('click', function() {
  const randomNumber = document.getElementById('randomNumber').innerText;
  
  const tempInput = document.createElement('input');
  document.body.appendChild(tempInput);
  tempInput.value = randomNumber;
  tempInput.select();
  document.execCommand('copy');
  document.body.removeChild(tempInput);

  const copyButton = document.getElementById('copyButton');
  copyButton.innerText = 'Copied!';
  setTimeout(() => {
    copyButton.innerText = 'Copy to Clipboard';
  }, 2000);
});

Final Output:

how-to-generate-random-number-in-html-css-and-javascript.gif

Conclusion:

Now you know how to create a simple, modern random number generator using HTML, CSS, and JavaScript. Whether you're building a quiz, a game, or any other application, this is a great feature to include. Plus, with the ability to style the UI and add dynamic features like number ranges or clipboard copying, you can make it even more useful for your users.

With just a few lines of code, you can now generate random numbers with a sleek UI that will engage your users!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺