Continuously loop through JavaScript text array onclick

12,341

Solution 1

Something like the following should do the trick:

<script type="text/javascript">
var nextWord = (function() {
  var wordArray = ['fe','fi','fo','fum'];
  var count = -1;
  return function() {
    return wordArray[++count % wordArray.length];
  }
}());

</script>

<p id="foo">&nbsp;</p>

<button onclick="
  document.getElementById('foo').innerHTML = nextWord();
">Update</button>

Edit

Radomised version:

var nextWord = (function() {
  var wordArray = ['fe','fi','fo','fum'];
  var copy;
  return function() {
    if (!copy || !copy.length) copy = wordArray.slice();
    return copy.splice(Math.random() * copy.length | 0, 1);
  }
}());

Solution 2

The following should do it http://jsfiddle.net/mendesjuan/9jERn/1

$(document).ready(function(){
  var arr = ["One","Two","Three"];
  var index = 0;
  $('#next').click(function(){ 
    $('#quote').html(arr[index]); 
    index = (index + 1) % arr.length ;
 });
});

Your code was writing all three values each time you clicked it (but only displaying that last value)

Solution 3

I think something like this would work

The javascript would look like:

// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];

function nextElement()
{
    textDisplayIndex += 1;
    if (textDisplayIndex > maxTextArrayIndex)
    {
        textDisplayIndex = 0;
    }

    document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}

The html would look like:

<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>
Share:
12,341
Staysee
Author by

Staysee

Updated on June 05, 2022

Comments

  • Staysee
    Staysee almost 2 years

    I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.

    Here's what I have

    $(document).ready(function(){
      var arr = new Array("One","Two","Three");
      var len=arr.length;
      $('#next').click(function(){ 
        for(var i=0; i<len; i++) { 
          $('#quote').html(arr[i]); 
        } 
     });
    });