Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
JavaScript Application For Random Number Generator
Next article icon

JavaScript Application For Random Number Generator

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a random number generator is a fun and practical project for beginners in JavaScript. It helps you learn how to handle user inputs, generate random values within a range, and dynamically update the user interface.

What We’re Going to Create

We’ll build a user-friendly application that allows users to:

  • Enter a minimum and maximum range for generating random numbers.
  • Generate a random number within the specified range.
  • Reset the inputs and results to start fresh.

The application will have a clean interface and intuitive controls, making it easy for anyone to use.

Project Preview

djnd
JavaScript Application For Random Number Generator

Random Number Generator - HTML and CSS

The HTML code creates the structure for a Random Number Generator web application, including input fields for the minimum and maximum range, a button to generate the number, and a button to reset the inputs. It also displays the generated random number dynamically on the page and the CSS Styles the generate button, reset button and the result displaying area.

HTML
<html> <head>   <style>     * {     margin: 0;     padding: 0;     box-sizing: border-box; }  body {     font-family: Arial, sans-serif;     display: flex;     justify-content: center;     align-items: center;     height: 300vh;     background-color: #f2f2f2; }  .container {     background-color: #fff;     border-radius: 10px;     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);     padding: 30px;     text-align: center;     width: 300px; }  h1 {     font-size: 24px;     margin-bottom: 20px; }  .input-section {     margin-bottom: 20px; }  input[type="number"] {     padding: 8px;     margin: 10px 5px;     width: 80px;     border: 1px solid #ccc;     border-radius: 5px; }  button {     padding: 10px 20px;     margin-top: 10px;     background-color: #4CAF50;     color: white;     border: none;     border-radius: 5px;     cursor: pointer;     font-size: 16px; }  button:hover {     background-color: #45a049; }  button:active {     background-color: #3e8e41; }  #randomNumber {     font-size: 24px;     font-weight: bold;     margin: 20px 0;     color: #333; }  #reset {     background-color: #f44336;     margin-top: 10px; }  #reset:hover {     background-color: #e53935; }   </style> </head> <body>     <div class="container">         <h1>Random Number Generator</h1>         <div class="input-section">             <label for="min">Minimum:</label>             <input type="number" id="min" value="1">             <label for="max">Maximum:</label>             <input type="number" id="max" value="100">         </div>         <button id="generate">Generate Random Number</button>         <div class="result">             <p id="randomNumber">Click the button to  generate</p>         </div>         <button id="reset">Reset</button>     </div> </body> </html> 

In this example

  • The container centers the app and styles the layout with a clean, minimal design.
  • The input fields allow users to specify the range (minimum and maximum numbers).
  • The buttons provide functionality to generate a random number or reset the form.
  • Styling includes hover and active effects to make the UI interactive and user-friendly.

Random Number Generator - JavaScript Logic

The JavaScript code powers the functionality of the Random Number Generator by handling user input, generating random numbers within the specified range, and updating the result display. It also provides a reset feature to clear inputs and the displayed number.

JavaScript
const min = document.getElementById('min'); const max = document.getElementById('max'); const genBtn = document.getElementById('generate'); const resetBtn = document.getElementById('reset'); const randNumDisplay = document.getElementById('randomNumber');  function genRandNum() {     const minVal = parseInt(min.value);     const maxVal = parseInt(max.value);      if (isNaN(minVal) || isNaN(maxVal) || minVal >= maxVal) {         alert("Please enter valid minimum and maximum values.");         return;     }      const randNum = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;     randNumDisplay.textContent = randNum; }  function reset() {     min.value = 1;     max.value = 100;     randNumDisplay.textContent = "Click the button to generate"; }  genBtn.addEventListener('click', genRandNum); resetBtn.addEventListener('click', reset); 

In this example

  • Variables like min, max, genBtn, resetBtn, and randNumDisplay are used to reference specific HTML elements.
  • The genRandNum() function fetches user input, validates the range, generates a random number, and updates the display dynamically.
  • The reset() function restores default values for inputs and resets the display text.
  • Event listeners connect the buttons to their respective functions for generating or resetting the random number.

Complete code

HTML
<html> <head>     <style>         * {             margin: 0;             padding: 0;             box-sizing: border-box;         }          body {             font-family: Arial, sans-serif;             display: flex;             justify-content: center;             align-items: center;             height: 300vh;             background-color: #f2f2f2;         }          .container {             background-color: #fff;             border-radius: 10px;             box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);             padding: 30px;             text-align: center;             width: 300px;         }          h1 {             font-size: 24px;             margin-bottom: 20px;         }          .input-section {             margin-bottom: 20px;         }          input[type="number"] {             padding: 8px;             margin: 10px 5px;             width: 80px;             border: 1px solid #ccc;             border-radius: 5px;         }          button {             padding: 10px 20px;             margin-top: 10px;             background-color: #4CAF50;             color: white;             border: none;             border-radius: 5px;             cursor: pointer;             font-size: 16px;         }          button:hover {             background-color: #45a049;         }          button:active {             background-color: #3e8e41;         }          #randomNumber {             font-size: 24px;             font-weight: bold;             margin: 20px 0;             color: #333;         }          #reset {             background-color: #f44336;             margin-top: 10px;         }          #reset:hover {             background-color: #e53935;         }     </style> </head> <body>     <div class="container">         <h1>Random Number Generator</h1>         <div class="input-section">             <label for="min">Minimum:</label>             <input type="number" id="min" value="1">             <label for="max">Maximum:</label>             <input type="number" id="max" value="100">         </div>         <button id="generate">Generate Random Number</button>         <div class="result">             <p id="randomNumber">Click the button to  generate</p>         </div>         <button id="reset">Reset</button>     </div>      <script>        // Select DOM elements const min = document.getElementById('min'); const max = document.getElementById('max'); const genBtn = document.getElementById('generate'); const resetBtn = document.getElementById('reset'); const randNumDisplay = document.getElementById('randomNumber');  // Function to generate a random number function genRandNum() {     const minVal = parseInt(min.value);     const maxVal = parseInt(max.value);      // Validate inputs     if (isNaN(minVal) || isNaN(maxVal) || minVal >= maxVal) {         alert("Please enter valid minimum and maximum values.");         return;     }      // Generate a random number within the range     const randNum = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;     randNumDisplay.textContent = randNum; }  // Reset the inputs and result function reset() {     min.value = 1;     max.value = 100;     randNumDisplay.textContent = "Click the button to generate"; }  // Event listeners genBtn.addEventListener('click', genRandNum); resetBtn.addEventListener('click', reset);      </script> </body> </html> 

Next Article
JavaScript Application For Random Number Generator

P

pranjalonj7
Improve
Article Tags :
  • HTML
  • JavaScript-Projects

Similar Reads

    HTML DOM crypto.getRandomValues() method
    The crypto getRandomValues() method lets you get cryptographic random values. The array given as the parameter to this method gets filled with cryptographic random numbers. Syntax: var a = window.crypto.getRandomValues(Array); Parameters: Array: An integer-based Array, can be Int8Array, UInt8Array,
    1 min read
    Random vs Secure Random numbers in Java
    Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Secur
    3 min read
    Online Random Number Generator
    Random Number Generator is a simple online tool used to generate random numbers between any two given numbers. Generate random positives with or without repeats within a custom range from 0 to 99999. This Random Number Generator is Easy to use and accurate, which can be used for a lot of fun activit
    3 min read
    Generating Random Numbers in Java
    Random numbers are widely used in programming for simulations, gaming, security, etc. There are multiple ways to generate random numbers using built-in methods and classes in Java. The most commonly used approaches are listed below:java.util.Random classMath.random() method (returns double values)Th
    4 min read
    Java.util.Random.nextInt() in Java
    Generating random numbers themselves has a good utility. Java provides a method Random.nextInt() which is the part of Random Class present in the util package. The nextInt() method is used to get the random integer values in the range of int.Syntaxint nextInt() int nextInt(int bound)int nextInt(int
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences