user3535075
user3535075

Reputation: 15

Random Number JavaScript In Span Tag

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

Answers (3)

Surinder ツ
Surinder ツ

Reputation: 1788

You have an syntax error in your anonymous function

Replace

myFunction()

with

function()

Rest of your code is error free.

Upvotes: 0

p.s.w.g
p.s.w.g

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

VisioN
VisioN

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

Related Questions