Skip to content Skip to sidebar Skip to footer

Making Random Numbers Write On The Page

I'm trying to create a function that first selects a random number, and then print every number starting at 1 through the random number, on the page. Basically, it should look som

Solution 1:

You have set the event listener in a wrong way.

document.getElementById('yourElement').onclick = randomNumber();

When you use "onclick = randomNumber()" you are not setting the function randomNumber to onclick. Because you wrote "()" after the function, you are actually calling the function and the thing that is set to onclick is actually the return value of randomNumber, which is in your case "undefined".

This piece of code should do what you want.

<scripttype="text/javascript">window.onload = function() {
            var english = {
                25 : 'twenty five'// and so on
            }

            functionrandomNumber() {
                var r = Math.round( Math.random() * 200 )
                return english[r] || r;
            }

            functionwriteRandomNumber() {
                this.innerHTML += randomNumber();
            }

            document.getElementById('yourElement').onclick = writeRandomNumber;
        }

    </script>

Solution 2:

Use innerText, innerHTML, or textContent to set the text of an element:

document.getElementById("myElement").innerText += num;

Post a Comment for "Making Random Numbers Write On The Page"