1

I'd like my code to show me the content of an array when I click on a button.

One click for array[0], second for array[1] etc. I got it, but I don't know how to disable the button (or just stop the function) when my array has run out of content. I tried some simple for loop, but it didn't work.

var writing = (function() {
  var myArray = ["one ", "two ", "three!"];
  var counter = -1;
  return function() {
    return myArray[counter += 1];
  }
})();

function buttonFunction() {
  document.getElementById('parag').innerHTML += writing();
}
<button onclick='buttonFunction()'>Click</button>
<p id="parag">...</p>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Adam M
  • 21
  • 3

3 Answers3

2

Try this

var counter = -1;

var writing = (function () {
      var myArray = ["one ","two ","three!"];
      return function(){return myArray[counter+=1];}
    })();

    function buttonFunction(self) {
    document.getElementById('parag').innerHTML += writing();
      if(counter == 2)
       self.disabled = true;
      }
<button onclick='buttonFunction(this)'>Click</button>
    <p id="parag">...</p>

Variable counter must be global to know the current count of clicks.

Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

Sorry for my initial mistake. Just check in your anonymous function returned by writing() method for counter reaching myArray.length. In that case, disable the button like this:

return function(){
  if(++counter < myArray.length)
    return myArray[counter];
  else
    return "";
}

or

return function(){
  if(++counter < myArray.length)
    return myArray[counter];
  self.disabled=true;
  return "";
}
Syntac
  • 1,687
  • 11
  • 10
0

Another approach which doesn't require keeping track of the index:

<button id="btn">Click</button>
<p id="parag">...</p>

<script>
    var myArray = ["one", "two", "three!"];

    var button = document.getElementById('btn');

    // If array is empty at the beginning, disable the button immediately
    if(myArray.length === 0) button.disabled = true;

    button.addEventListener('click', function(event) {

      document.getElementById('parag').innerText += myArray.shift();
      if(myArray.length === 0) this.disabled = true;

    });

</script>

myArray.shift() removes the first element from the array (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) and then you check if the Array is empty and if so, you disable the button.

Btw. Don't use onClick directly on elements (Why is using onClick() in HTML a bad practice?)

Community
  • 1
  • 1
user3210641
  • 1,565
  • 1
  • 10
  • 14