Search code examples
javascriptjqueryhtmlinnerhtml

How to change innerHTML without refresh or refresh and output with same button in javascript


I am trying to create a random phrase generator with words. My problem is to get a new phrase I have to refresh the page first and then it creates a new phrase. I want it to generate phrase without refreshing whole page or at least generate and refresh with same button here is my code.

var output = "hai " + randomBodyPart + " come un "  + randomWord + " " + randomAdjective + "!";

//Pagereloder
            function myFunction() {
                location.reload();
            }

//Genretor Button
          var button = document.querySelector("button");
          button.addEventListener("click", function() {
                (document.getElementById("viewer").innerHTML= output);
          });

and here is HTML

<article>
                <header>
                    <h1>Random word Genretor</h1>
                    <p class="gen-button"><button class="btn">Click me</button><button class="btn" onclick="myFunction()">Relod</button></p>
                    <h2 id="viewer">Here</h2>
                </header>

Solution

  • Throw your code into a function and make the button call that function:

                function myFunction() {
                    var output = "hai " + randomBodyPart + " come un "  + randomWord + " " + randomAdjective + "!";
                    document.getElementById("viewer").innerHTML= output
                }
    
    //Genretor Button
              var button = document.querySelector("button");
              button.addEventListener("click", function() {
                    myFunction();
              }); 
    

    Also, the random generators must be inside thy function also.