So, I'm a beginner programmer and figured I could do something short and fun. I made a short program in like 5 minutes, but I ran into a problem where I can't figure out, how to make a button that runs a said script when pressed (e.g. makes an alert with a random number in it) Here's my code
<!DOCTYPE html>
<html>
<Head>
<h2>
Random number Generator
</h2>
</Head>
<body>
<script src ="Script.js"></script>
<button type="button" onclick="alert(randomNum)"> Generate! </button>
</body>
</html>
and the script part here
function randomNum(result, oneToHundred, randomNum) {
let newNumber = Math.random()
let oneToHundred = newNumber * 1000
let result = Math.floor(oneToHundred)
return result
};
alert(randomNum)
I just can't figure out how to make the button search for a script and run it when pressed. I tried to embed the script search to the onclick part, but i got a syntax error.
<button id="my-btn" onClick="myFunction()"></button>) to JS's .addEventListener() method (eg<button id="my-btn"></button> <script>let myBtn = document.getElementById("my-btn"); myBtn.addEventListener("click", myFunction)</script>). MDN likes this way bc it lets you add many listeners, gives finer control of listener timing, and works on any event target -- plus it keeps JS out of HTML. (I can write a better example if you like.)