I have a randomiser that outputs a sentence - from arrays - on button click (working), but clicking for a second time outputs the exact same sentence

Viewed 66

Introduction/What I Would Like to Achieve

The sentence generator is fully-functional, and will generate a random sentence from the words in the arrays, whenever you refresh the page or click the button for the first time. While clicking the button for the second time appears not to work, what it's actually doing is generating the exact same sentence and replacing the previous one. This is more clearly seen if you change = truth inside of the onclick function to += truth, where it'll output the exact same sentence without overwriting the previous one. What I would like is for it to output a new random sentence, in place of the previous, each time I click the button.

<!DOCTYPE html>
<html>
  <head>
    <title>Randomiser Example</title>
  </head>
  <body>
    <section>
      <div id="random"></div>
      <button id="reload">get a new sentence!</button>
      <p><span id="serving"></span> Permuations</p>
    </section>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
      /* word bank */
      var article, word1, word2, word3, conjunction, word4;
      article = ['The', 'Your', 'This'],
         word1 = ['apple', 'orange', 'grape'],
         word2 = ['pineapple','mango','banana'],
         word3 = ['melon', 'avocado', 'raspberry'],
         conjunction = ['and', 'because', 'but', 'as', 'since'],
         word4 = ['blueberry', 'gooseberry', 'tangerine'];
      /* randomiser */
      for (var i = 0; i <= 0; i++) {
         var article_rnd, word1_rnd, word2_rnd, word4_rnd, word3_rnd, conjunction_rnd, space;
         article_rnd = Math.floor(Math.random() * article.length);
         word1_rnd = Math.floor(Math.random() * word1.length);
         word2_rnd = Math.floor(Math.random() * word2.length);
         word4_rnd = Math.floor(Math.random() * word4.length);
         word3_rnd = Math.floor(Math.random() * word3.length);
         conjunction_rnd = Math.floor(Math.random() * conjunction.length);
         space = ' ';
      /* permutations */
         var csv = (function() {
               return function(n) {
                  return Intl.NumberFormat().format(n);
               };
            })
            ();
         var really = article.length * word1.length * word2.length * word3.length * conjunction.length * word4.length;
         var serving = csv(really);
      /* random sentence */   
        var truth = '&quot' + article[article_rnd] + space + word1[word1_rnd] + space + word2[word2_rnd] + space + word3[word3_rnd] + space +
            conjunction[conjunction_rnd] + space + word4[word4_rnd] + '&quot';

         document.getElementById('random').innerHTML = truth;
         document.getElementById('serving').innerHTML = serving; /* permutations */
         document.getElementById('reload').onclick = function() {
            document.getElementById('random').innerHTML = truth;
         };
      };
    </script>
  </body>
</html>

What I have tried

My knowledge of JavaScript is somewhat limited (read: very), thusly so are my attempted solutions. My initial solution was to simply do away with the button as it is, and load the script into the page using an iFrame, where'd I'd then have a button that'd simply reload the frame and generate a sentence that way. This, of course, works, but isn't ideal. My other solution was to wipe the previous sentence before generating the new one, which didn't work. I thought having a sentence generate when the page loaded might have been conflicting with the one generated when you press the button, but removing that line of code has no effect either.

I have searched far and wide (including here), and all I've been able to track down that seems remotely in my ball park is a question from 3 years ago, where the generator is more simplistic and where the asker wants an ever-so slightly different outcome. I assume there would be a way to check the newly generated sentence against the previous one and force it to output a new one. I also assume there is a much simpler way that I have already missed 15 times that will make me feel silly.

3 Answers

Your index values are not being recalculated when you click the button, instead they are being calculated only once on load. The choosing of random words and constructing of your "truth" sentence should be wrapped into a function which returns "truth" and is called as part of the onclick.

<!DOCTYPE html>
<html>

<head>
    <title>Randomiser Example</title>
</head>

<body>
    <section>
        <div id="random"></div>
        <button id="reload">get a new sentence!</button>
        <p><span id="serving"></span> Permuations</p>
    </section>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        /* word bank */
        var article, word1, word2, word3, conjunction, word4;
        article = ['The', 'Your', 'This'],
            word1 = ['apple', 'orange', 'grape'],
            word2 = ['pineapple', 'mango', 'banana'],
            word3 = ['melon', 'avocado', 'raspberry'],
            conjunction = ['and', 'because', 'but', 'as', 'since'],
            word4 = ['blueberry', 'gooseberry', 'tangerine'];
        /* randomiser */
        function randomizer() {
            for (var i = 0; i <= 0; i++) {
                var article_rnd, word1_rnd, word2_rnd, word4_rnd, word3_rnd, conjunction_rnd, space;
                article_rnd = Math.floor(Math.random() * article.length);
                word1_rnd = Math.floor(Math.random() * word1.length);
                word2_rnd = Math.floor(Math.random() * word2.length);
                word4_rnd = Math.floor(Math.random() * word4.length);
                word3_rnd = Math.floor(Math.random() * word3.length);
                conjunction_rnd = Math.floor(Math.random() * conjunction.length);
                space = ' ';
                /* permutations */
                var csv = (function () {
                    return function (n) {
                        return Intl.NumberFormat().format(n);
                    };
                })
                    ();
                var really = article.length * word1.length * word2.length * word3.length * conjunction.length * word4.length;
                var serving = csv(really);
                /* random sentence */
                var truth = '&quot' + article[article_rnd] + space + word1[word1_rnd] + space + word2[word2_rnd] + space + word3[word3_rnd] + space +
                    conjunction[conjunction_rnd] + space + word4[word4_rnd] + '&quot';

                document.getElementById('random').innerHTML = truth;
                document.getElementById('serving').innerHTML = serving; /* permutations */


            };
            return truth;
        }
        document.getElementById('reload').onclick = function () {
            document.getElementById('random').innerHTML = randomizer()
        };

        document.addEventListener("DOMContentLoaded", function (event) {
            // - Code to execute when all DOM content is loaded. 
            // - including fonts, images, etc.
            document.getElementById('random').innerHTML = randomizer()
        });
    </script>
</body>

</html>

You need to first wrap your randomizer code into a function, the randomizer function in my snippet and then call the function on the event listener for DOMContentLoaded first. Call it again within the event handler.

wrap it inside function then onclick call that function

<!DOCTYPE html>
<html>

<head>
  <title>Randomiser Example</title>
</head>

<body>
  <section>
    <div id="random"></div>
    <button id="reload">get a new sentence!</button>
    <p><span id="serving"></span> Permuations</p>
  </section>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script>
    function truth_generate(){
    /* word bank */
    var article, word1, word2, word3, conjunction, word4;
    article = ['The', 'Your', 'This'],
      word1 = ['apple', 'orange', 'grape'],
      word2 = ['pineapple', 'mango', 'banana'],
      word3 = ['melon', 'avocado', 'raspberry'],
      conjunction = ['and', 'because', 'but', 'as', 'since'],
      word4 = ['blueberry', 'gooseberry', 'tangerine'];
    /* randomiser */
    for (var i = 0; i <= 0; i++) {
      var article_rnd, word1_rnd, word2_rnd, word4_rnd, word3_rnd, conjunction_rnd, space;
      article_rnd = Math.floor(Math.random() * article.length);
      word1_rnd = Math.floor(Math.random() * word1.length);
      word2_rnd = Math.floor(Math.random() * word2.length);
      word4_rnd = Math.floor(Math.random() * word4.length);
      word3_rnd = Math.floor(Math.random() * word3.length);
      conjunction_rnd = Math.floor(Math.random() * conjunction.length);
      space = ' ';
      /* permutations */
      var csv = (function() {
          return function(n) {
            return Intl.NumberFormat().format(n);
          };
        })
        ();
      var really = article.length * word1.length * word2.length * word3.length * conjunction.length * word4.length;
      var serving = csv(really);
      /* random sentence */
      var truth = '&quot' + article[article_rnd] + space + word1[word1_rnd] + space + word2[word2_rnd] + space + word3[word3_rnd] + space +
        conjunction[conjunction_rnd] + space + word4[word4_rnd] + '&quot';
      document.getElementById('random').innerHTML = truth;
      document.getElementById('serving').innerHTML = serving; /* permutations */
    };
    return truth;
    }
    document.getElementById('reload').onclick = function() {
      document.getElementById('random').innerHTML = truth_generate();
    };
document.getElementById('random').innerHTML = truth_generate();
  </script>
</body>

</html>

Related