šØāš»Ā Daily Code 47 | Random Number 1-100, š Python and šØ JavaScript (2)
So as promised yesterday, Iām going to try this random number exercise again without ChatGPT. In Python I just generate the number and show it in the console, but in JavaScript I want to have a button in the browser to generate it and then also show it in the browser.
Letās see how far I get!
My Code
Python
# Randomly generate a number between 1 and 100
import random
def main():
print(random.randint(1, 100))
if __name__ == '__main__':
main()
Python was super easy for me now. Took me less than a minute. Really the only thing you need to know is random.randint().
JavaScript
Now JS is where it got harderā¦ Below is exactly how far I came without any help until I started struggling. How does that work again with .onclickā¦? I canāt just use it as a function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
</head>
<body>
<button id="js-button">Generate random number</button>
<div id="js-output"></div>
<script>
document.getElementById('js-button').onclick /* ...
</script>
</body>
</html>
Alright ChatGPT to the rescue again!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
</head>
<body>
<button id="js-button">Generate random number </button>
<div id="js-output"></div>
<script>
document.getElementById('js-button').onclick = function () {
let randomNumber = Math.floor(Math.random() * 100) + 1;
document.getElementById("js-output").textContent = randomNumber;
}
</script>
</body>
</html>
Alright it turns out instead of just calling
.onclick
as a function I just need to somehow use it with= function () {}
.And then the math works with
Math.floor(Math.random() * 100) + 1
.And lastly
.textContent = randomNumber
Alright if I can remember these three things I think I should be able to do this exercise out of my head and without any help. Iāll try exactly that tomorrow!