Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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>
like image 767
Marie Avatar asked Oct 29 '25 13:10

Marie


1 Answers

You could omit the for loop, because it iterates to the end and the last item is shown.

Take a global variable index instead and increment and adjust by the length of the array to get only valid values of the array.

BTW, a single return statement at the end of the function without a different value than undefined is not necessary because in Javascript returns any function undefined, as long as it is not used as constructor (in connection with new). Then it is not necessary if the returned vaue is never used.

var texts = ["one", "two", "three", "four", "five"],
    btn = document.getElementById("myBtn"),
    text = document.getElementById("myText"),
    index = 0;

btn.addEventListener("click", changeText);
text.innerHTML = texts[0];

function changeText() {
    index++;
    index %= texts.length
    text.innerHTML = texts[index];
}
<p id="myText"></p>
<button type="button" id="myBtn">Start</button>
like image 192
Nina Scholz Avatar answered Nov 01 '25 03:11

Nina Scholz



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!