Reputation: 15
I'm trying to create a random number in a span tag, how would I go about doing this? I've been trying but I'm sure I'm missing something.
<div><span id="people">2 </span>Is a random number</div>
and my JS is
window.onload = myFunction() {
var x = Math.floor((Math.random() * 9) + 2);
document.getElementById("people").innerHTML = x;
}
Upvotes: 1
Views: 1585
Reputation: 1788
You have an syntax error in your anonymous
function
Replace
myFunction()
with
function()
Rest of your code is error free.
Upvotes: 0
Reputation: 149040
To create an anonymous function in an expression, use function() {...}
, like this:
window.onload = function() {
var x = Math.floor((Math.random() * 9) + 2);
document.getElementById("people").innerHTML = x;
}
Alternatively, to use a named function, it would look like this:
function myFunction() {
var x = Math.floor((Math.random() * 9) + 2);
document.getElementById("people").innerHTML = x;
}
window.onload = myFunction;
Upvotes: 1
Reputation: 145428
The problem is a syntax error when you define an anonymous function:
// -------------v
window.onload = function() {
var x = Math.floor((Math.random() * 9) + 2);
document.getElementById("people").innerHTML = x;
};
If you want to give a name for your anonymous function you may do:
function myFunction() {
var x = Math.floor((Math.random() * 9) + 2);
document.getElementById("people").innerHTML = x;
}
window.onload = myFunction;
Upvotes: 1