I want to generate random number between 0 to 100 and show a div
tag if that random isn't less than 10. I have this code but it doesn't work, please can you help me fix the error.
I have already tried on google but I can not find code for php
function showbox(){ document.getElementById("ap1").style.visibility = "visible"; } function myFunction(name) { var x = document.getElementById("demo") x.innerHTML = Math.floor((Math.random() * 100) + 1); } if(myFunction(<=10){ setTimeout(showbox, 35000); }
<div id="ap1" style="visibility: hidden;"></div>
Your code has SyntaxError
. You can use this code
var element = document.getElementById("ap1"); var random = Math.floor((Math.random() * 100) + 1); element.innerHTML = random; if (random >= 10){ document.getElementById("ap1").style.visibility = "visible"; } else console.log(random);
<div id="ap1" style="visibility: hidden;"></div>
Math.floor((Math.random() * 100) + 1)
generate number between 1 and 100
. If you want to generate number between 0 and 100
use Math.floor((Math.random() * 101))
or Math.round((Math.random() * 100))
Try this . The code wasn't correct. You used demo
id but you have ap1
, and the if
condition also was wrong in JavaScript.
The JavaScript code:
function myFunction(name) {
var x = document.getElementById("ap1")
var randomNum = Math.floor((Math.random() * 100) + 1);
if (randomNum > 10) {
x.innerHTML = randomNum;
} else {
x.innerHTML = 'empty';
}
}
setTimeout(myFunction, 350);
you need to close myFunction
in the if
and you need to return
in myFunction
:-
function showbox(){ document.getElementById("ap1").style.visibility = "visible"; } function myFunction(name) { var x = document.getElementById("ap1") return x.innerHTML = Math.floor((Math.random() * 100) + 1); } if(myFunction() <= 10){ setTimeout(showbox, 35000); }
<div id="ap1" style="visibility: hidden;"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.