Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuously loop through JavaScript text array onclick

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]); 
    } 
 });
});
like image 256
Staysee Avatar asked Jul 08 '26 01:07

Staysee


2 Answers

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);
  }
}());
like image 161
RobG Avatar answered Jul 10 '26 14:07

RobG


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)

like image 31
Juan Mendes Avatar answered Jul 10 '26 13:07

Juan Mendes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!