javascript

Display elements of an array one by one in order on event click


i want to show each item one by one on event click by order. By default it is the first element, when button is clicked it should show second one, after third etc...When it reaches the last element, it should repeat again and it should always show by order after click.

var texts = ["one", "two", "three", "four", "five"];

var btn = document.getElementById("myBtn");
btn.addEventListener("click", changeText);
var text = document.getElementById("myText");
text.innerHTML = texts[0];

function changeText(){

	for( var i = 0; i < texts.length; i++ ){
		text.innerHTML = texts[i];
	}
	return;
}
<p id="myText"></p>
<button type="button" id="myBtn">Start</button>


Solution

  • Fist of all you do not required to iterate all element of an array.If elements are in order then it can be achieve using index of the current element.We can get index of current element using indexOf method on an array. Below are the steps:

    Step 1. Get index of current element using indexOf method on an array.

    Step 2.Increment index by 1.

    Step 3.Check if index is not the last index of array(in case of last index set index as 0).

    Step 4.Get the element from array based on index and set in the document element.

    Here is my running code snippet:

    var texts = ["one", "two", "three", "four", "five"];
     var text=document.getElementById("myText");
    var btn = document.getElementById("myBtn");
    btn.addEventListener("click", changeText);
     text.innerHTML = texts[0];
    
    
        function changeText(){
           var searchTerm =  text.innerHTML  ;
           var index=texts.indexOf(searchTerm)+1;
           if(index == texts.length )index=0;
              var result=texts[index];
              text.innerHTML = result;
        	  return;
           }
    <p id="myText"></p>
    <button type="button" id="myBtn">Start</button>