top of page
Writer's pictureWeb Coding

How to create a random number generator

Learn how to create a random number generator with HTML, CSS and JavaScript


HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <div id="content">
 <p id="numberGenerated">0</p>
 <button type="button" id="generateBtn">Generate</button>
 <div> Range: <input type="number" name="range" id="range"> </div>
 </div>

 <script src="script.js"></script>
</body>
</html>

CSS

*{
 margin0;
 padding0;
}

body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
}

#content{
 displayflex;
 align-itemscenter;
 justify-contentcenter;
 flex-directioncolumn;
}


JavaScript

let generateBtn = document.getElementById('generateBtn');
let numberDisplay = document.getElementById('numberGenerated');
let range = document.getElementById('range');

generateBtn.addEventListener('click'calculate);

function calculate(){
 let numberRange = range.value;

 if(numberRange == false){
 numberRange = 10;
 numberDisplay.innerHTML = Math.round(Math.random() * numberRange);
    }
 else {
 numberDisplay.innerHTML = Math.round(Math.random() * numberRange);
    }
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding

2 views

Comments


bottom of page