0

I'd like to have a page with a button and when I click the button the text should be shown. the text is taken from different arrays randomly with Javascript. Everything works in my project except one thing: On the first load of the page I see no text just the button. How do I make so that one of the arrays is randomly chosen and displayed on the fist page load (without click on the button)

<!DOCTYPE html>
<html>

<head>
    <script>
        function myFunction() {
            var quotes = [{
                text: " <br>    1   <br><br>    2   <br><br>    3   ",
            }, {
                text: " <br>    4   <br><br>    5   <br><br>    6   ",
            }, {
                text: " <br>    7   <br><br>    8   <br><br>    9   ",
            }, ];
            var quote1 = quotes[Math.floor(Math.random() * quotes.length)];
            document.getElementById("quote1").innerHTML =
                '<p><font size="7">' + quote1.text + '</font></p>';
        }
    </script>
</head>

<body>
    <center>
        <div id="quote1"></div>
        <br>
        <br>
        <br>
        <br>
        <br>
        <center>
            <a href="#" onclick="myFunction()">Next</a>
        </center>
    </center>
</body>

</html>

Thank you!

1
  • Just trigger the button on page load, or call myFunction(). Commented May 31, 2014 at 13:46

3 Answers 3

2

Call it on page load.

window.onload = function(){
   myFunction();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Call the function after page is loaded.

<body onload="myFunction()">

Comments

0

put the entire stuff in to a function at the end of the doc:

<!DOCTYPE html>
<html>
<head>

</head>

<body>
<center>
<div id="quote1"></div>
<br>
<br>
<br>
<br>
<br>
<center>
<a href="#" onclick="randomQuote()">Next</a>
</center>
</center>
</body>

<script>
var randomQuote = function() {
    var quotes = [
       {text:" <br>    1   <br><br>    2   <br><br>    3   ",},
       {text:" <br>    4   <br><br>    5   <br><br>    6   ",},
       {text:" <br>    7   <br><br>    8   <br><br>    9   ",},
     ];
     var quote1 = quotes[Math.floor(Math.random() * quotes.length)];
     document.getElementById("quote1").innerHTML=
          '<p><font size="7">' + quote1.text + '</font></p>';
 };
 randomQuote();

</script>
</html>

The last line will execute the function immediately.

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.