Hello Coders, In this article we are going to build this Random Number Generator using HTML, CSS and JavaScript.
Below I have provided both step by step article guide as well as Complete video tutorial for you. You can download the complete source code of this project by clicking on the download button at the bottom of this article.
Create a Random Number Generator using JavaScript | Video Tutorial
In the above video I have explained each and every line of code. If you are a complete beginner or having trouble understanding this article then consider watching the above tutorial.
Build a Random Number Generator using JavaScript | Step by Step Article Guide
Project Setup :Â
Create three files. index.html, styles.css, script.js. Generate the boiler plate html and link css file and js file. I will be adding a font family “sans-serif” and clearing out the default margin and padding applied by the browser.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Random Number Generator</title> <link rel="stylesheet" href="styles.css" /> </head> <body></body> </html>
styles.css
* { font-family: sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
Adding HTML & CSS :
Lets start adding html. Inside the html we will have h1, span and a button. Span and Button will have their Id so that we can select them using JavaScript. Then we will add all the necessary styling to make it look good.
index.html
<div class="container"> <h1>Random Number Generator</h1> <span id="number">0</span> <button id="generateBtn">Generate</button> </div>
styles.css
body { background-color: #eee; height: 100vh; display: flex; align-items: center; justify-content: center; } .container { background-color: #fff; padding: 2rem; border-radius: 1rem; text-align: center; border: 0.1rem solid #000; } .container h1 { margin-bottom: 1rem; } .container span { display: block; margin-bottom: 1rem; font-size: 8rem; color: orangered; } .container button { outline: none; border: none; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 1rem; background-color: #000; color: #fff; cursor: pointer; }
Adding JavaScript :
We will get access to number and generateBtn. We will generate a random number using Math object provided by JavaScript and then we will update the generated number to the DOM.
script.js
const number = document.getElementById('number'); const generateBtn = document.getElementById('generateBtn'); const randomNumberGenerator = () => { const randomNumber = Math.floor(Math.random() * 10 + 1); number.textContent = randomNumber; }; generateBtn.addEventListener('click', randomNumberGenerator); randomNumberGenerator();
Congratulations! on completing this project. Hope you learnt something from this article. If you have any doubts, feel free to ask them below in comment section.