user3242704
user3242704

Reputation: 37

How do i Make a load more button

I wake to to Create a button.. Everytime the user click on The load more buttom i want it to keep The number is ++ so on and so on.. But so far it gotten to ten i dont know how to make it load more without stopping everytime the user click on the button heres the code i have so far

<!DOCTYPE html>
<html>
    <body>

        <p>Click the button to loop through a block of code five times.</p>
        <button onclick="myFunction()">Load More</button>
        <p id="demo"></p>
        <script>
            function myFunction() {
                var y="";
                for (var i=0;i<10;i++) {
                    y=y + "The number is " + i + "<br>";
                }
                document.getElementById("demo").innerHTML=y;
            }
            var x="";
            for (var i=0;i<5;i++) {
                x=x + "The number is " + i + "<br>";
            }
            document.getElementById("demo").innerHTML=x;
        </script>

    </body>
</html>

Upvotes: 1

Views: 2458

Answers (2)

Nate Kibler
Nate Kibler

Reputation: 652

You need to declare your counter variable outside of your function for this to work. Try this: JSFiddle

<script type="text/javascript">
    var i = 0;
    function myFunction() {
        var y="";
        for (var j = 0;j < 5;j++)
        {
            y=y + "The number is " + i + "<br>";
            i++;
        }
        var inner = document.getElementById("demo").innerHTML;
        document.getElementById("demo").innerHTML=inner + y;
    }

    var x="";
    for (;i<5;i++)
    {
        x=x + "The number is " + i + "<br>";
    }
    document.getElementById("demo").innerHTML=x;
</script>

Upvotes: 0

mwallisch
mwallisch

Reputation: 1810

in the code you posted x and y only exist inside your function myFunction if you want to keep the state of x and y you need to move the declaration of x and y outside of your function like so

...
<script>
// declare x and y outside of myFunction
// this makes them javascript globals (which is considered bad practice tough)
var x = "";
var y = "";

function myFunction()
{
  for (var i=0;i<10;i++)
  // ...
  // do your stuff with x and y
}
</script>

Upvotes: 1

Related Questions