1

I have an array with 13 items, all of it is text. I can show text from the array by using.

document.write(arrayname["0"]);

however I would like to have users click a button and fade out the current array item and load in the next array item. I wanted to have users not be able to view an array item less than 0 and more than 13 since that would cause an error.

I tried this but could not get it to work.

Thank you in advance.

<script type=text/javascript>

 var stuff=['item', 'stuff', 'thingamajig'];
 var counter=0;
 function goRight(){
    if(counter===13){
      counter=13;
    } else 
     { counter=counter+1 }
 }

 document.write(stuff[counter]);
</script>

 <img src="left.png"><img onclick="goRight(); src="right.png>
user2684521
  • 350
  • 4
  • 18

3 Answers3

1

Your largest source of confusion is probably due to not actually writing anything in your function. Try something like this:

<script type=text/javascript>
  var stuff=['item', 'stuff', 'thingamajig'];
  var count = 0;

  function goRight() {

    if (count > stuff.length - 1)
      count = 0;

    document.write(stuff[count++]);

  }

  document.write(stuff[count]);
</script>


<img src="left.png"><img onclick="goRight(); src="right.png>
Jason Tolliver
  • 299
  • 3
  • 8
0

Fiddle Demo

Try this

var stuff=['item', 'stuff', 'thingamajig'];
     var counter=0;

     function goRight(){
        document.write(stuff[counter]);
         counter++;
         if(counter===13){  // if You want 13 th element you check to 14
         counter=0;
         }
      }        

OR

var stuff=['item', 'stuff', 'thingamajig'];
     var counter=-1;
     goRight();

function goRight(){

         if(counter===13){
         counter=0;
         }else{
         counter++;
         }
        }      

   document.write(stuff[counter]);
Balachandran
  • 9,277
  • 1
  • 13
  • 25
0

Try something like this HTML

<span id='dynamicText'>item</span>
<button type='button' onclick='goRight()'>Click</button>

SCRIPT

var stuff = ['item', 'stuff', 'thingamajig'];
var counter = 1;
function goRight() {
 if(counter>= stuff.length)
    counter=0;
 document.getElementById('dynamicText').innerHTML=stuff[counter];
 counter++;
}

JSFiddle Demo

You might want to read Why Using document.write is a considered a bad practive

Community
  • 1
  • 1
T J
  • 40,740
  • 11
  • 73
  • 131