Lucinka
Lucinka

Reputation: 9

Generating random numbers and displaying them in a div after the page loads (DOM js)

I'm trying to generate random number and display it in a div every time when the page loads. The problem is it doesn't work and on top of that the js console in the browser has a problem with some of the tokens. I think they're right (code below) but even if I try to change them, it still says the same thing. Do you know where is the problem? Thank you!

window.addEventListener('load', function() {
  function generateRandomNumber();
  document.querySelector("#text").textContent = "The number is " + rnum + ".";
})

function generateRandomNumber() {
  var rnum = (Math.floor(Math.random() * 20) + 1);
  return rnum;
}
<div id="count">
  <div id="text">
  </div>
</div>

Upvotes: 0

Views: 35

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

There was an issue with the way you were calling the function generateRandomNumber() you do not need to use the function keyword before calling a JavaScript function. Also the variable rnum was not declared before using it.

<div id="count">
        <div id="text">
        </div>
 </div>

<script>

 window.addEventListener('load', function() {
       var rnum = generateRandomNumber (); //rnum was not defined here
       document.querySelector("#text").textContent = "The number is "+ rnum + "."; 
 })
 function generateRandomNumber () {
       var rnum = (Math.floor(Math.random() * 20) + 1);
       return rnum;
 }

</script>

Upvotes: 5

Related Questions