Amrinder Singh
Amrinder Singh

Reputation: 23

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>

Upvotes: 1

Views: 4670

Answers (2)

Lucas Tettamanti
Lucas Tettamanti

Reputation: 1810

<button id="myButton">Click to change the number</button>
<span id="randomNumber"></span>
<script type="text/javascript">
    (function(d) {
        var button = d.getElementById("myButton");
        var textNumber = d.getElementById("randomNumber");
        button.addEventListener("click", function(evt) {
            textNumber.innerHTML = _randomNumber();
        });

        var _randomNumber = function() {
            return Math.floor((Math.random() * 10) + 1);
        }
    })(document);
</script>
  1. Create the button and the container for the random text.
  2. Capture both elements.
  3. Add a listener to the button.
  4. When someone click the button you want to change the innerHtml, so, do it in the callback.
  5. I change the innerHtml with random numbers... its an example right =)
  6. The param evt its there because if you want to do something else with the event, you can erase that if you want.
  7. I give you a Bunny too:
  8. (|_/)
  9. ( #.*)
  10. c(")(")
  11. ENJOY!

Upvotes: 1

Kriggs
Kriggs

Reputation: 3778

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.

Upvotes: 0

Related Questions