Technologies:
Tolerim
25 days ago
How can I make my button tag execute a function?
Answers(2)
Vogi
22 days ago
Verified Answer
You can use the following code to display a random number on the p tag in DOM without the need for you to refresh the page continually:
<!DOCTYPE html>
<html>
<head>
<title>Random Number Generator</title>
</head>
<body>
<p id="random-number"></p>
<button onclick="generateRandomNumber()">Generate Random Number</button>
<script>
function generateRandomNumber() {
const randomNumber = Math.floor(Math.random() * 100);
document.getElementById("random-number").innerHTML = randomNumber;
}
</script>
</body>
</html>
This code generates a random number between 0 and 100 when the button is clicked and displays it on the p tag with id "random-number" without refreshing the page.
I hope this helps! Let me know if you have any other questions.
Sources
javascript - Random number generator w/ button - Stack Overflowtrying to get a random number on button click - Stack OverflowSolved: Creating random numbers on button click - QlikHTML DOM Button Object - W3SchoolTolerim
25 days ago
To call a function that displays a random number on the p tag in DOM when clicking a button, you can pass the function as an argument to the addEventListener method of the button element in your JavaScript code. Here's an example:
<!-- HTML code with a button and a p tag -->
<button id="generate-btn">Generate Number</button>
<p id="random-number"></p>
// JavaScript code to display random number on button click
const btn = document.getElementById('generate-btn');
const output = document.getElementById('random-number');
function generateRandomNumber() {
const randomNum = Math.floor(Math.random() * 10) + 1;
output.innerHTML = randomNum;
}
btn.addEventListener('click', generateRandomNumber);
In this example, we select the button element and the p tag using their respective IDs in the HTML code. We define the generateRandomNumber function which generates a random number using the Math.random() method and displays it on the p tag using the innerHTML property. Finally, we add an event listener to the button using the addEventListener method to listen for the click event and call the generateRandomNumber function when the button is clicked.