3

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>

1
  • Check the console: Uncaught SyntaxError: Unexpected token <= Commented Jun 16, 2016 at 8:20

3 Answers 3

1

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))

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.