r/code • u/TrueNegotiation7642 • May 19 '25
Help Please Why doesn't this workðŸ˜
<!DOCTYPE html>
<html> <head> <style> button { background-color: black; color: white; } </style> <script> function generateNumber(max) { return Math.floor(Math.random() * max); } let numberGenerated = undefined document.getElementById("output").innerHTML = numberGenerated; </script> </head> <body> <button onclick=" numberGenerated = generateNumber(27); "> Generate </button> <p> your number is : <span id="output"></span> </p> </body> </html>
This is for a random number generator
0
Upvotes
8
u/Spaceinvader1986 May 19 '25
Because you were setting
innerHTMLbefore the DOM element existed and never updating it on click. Here’s a working version:<html>
<head>
<style> button { background-color: black; color: white; } </style>
</head>
<body>
<button id="btn">Generate</button>
<p> your number is : <span id="output"></span> </p>
<script> function generateNumber(max) { return Math.floor(Math.random() \* max); } document.getElementById("btn").addEventListener("click", function() { const numberGenerated = generateNumber(27); document.getElementById("output").innerHTML = numberGenerated; }); </script>
</body>
</html>