This content originally appeared on DEV Community and was authored by Amy Oulton
Today we're going to build out a random number generator using JavaScript.
I went ahead and started with some simple HTML:
<div class="cont">
<h2 id="number">0</h2>
<button class="btn" id="generate">Random Number</button>
</div>
I also added in some styles because they never made anything worse! ?
body {
background-color: #00242e;
}
.cont {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 100px;
}
.btn {
background-color: #32edd7;
border: none;
padding: 16px 32px;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
.btn:hover {
background-color: #2ad1bd;
}
#number {
font-size: 28px;
color: pink;
}
Next we'll begin writing out our JavaScript!
We start by writing two variables, num
and btn
and assign them to the correct node.
const num = document.getElementById('number');
const btn = document.getElementById('generate');
We'll then go ahead and create our function. We'll be using the built in .random
method on the Math object.
const randomNum = () => {
return Math.floor(Math.random() * 1000);
};
Next, we wanna add an event listener on the button to listen for whenever it's clicked. We can do that as follows:
btn.addEventListener('click', () => {
});
Now within the body of this, we want to add the logic that replaces the current num
with a random number, as produced by the randomNum
function.
btn.addEventListener('click', () => {
num.innerHTML = randomNum();
});
Make sure you assign it to num.innerHTML
and not num
. Otherwise, we'll be overwriting the num
variable and not updating the actual number visible on the page.
For a clearer explanation, visit the tutorial on CodeCast. Here you can watch my video tutorial, as well as the code I'm writing in the video.
Be sure to leave me a comment there letting me know your thoughts, or what you would have done different!
For more information on CodeCast check out https://info.codecast.io/ ?
This content originally appeared on DEV Community and was authored by Amy Oulton

Amy Oulton | Sciencx (2021-09-07T22:14:53+00:00) Build A Random Number Generator w. JavaScript. Retrieved from https://www.scien.cx/2021/09/07/build-a-random-number-generator-w-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.