Display elements one by one from an array using jQuery

Introduction

I will show you in this example, how to display elements one by one from an array using jQuery. Let’s say you have a button on the web page and on clicking the button the values from array will be displayed one by one. There are two examples below, one simply access the values from an array and another displays the images from an array.

Prerequisites

jQuery 1.11.1/3.5.1

HTML Part

In our HTML code snippets I have just one div with button on the web page for clicking on it.

<div id="text-center">
	<button type="submit" id="btn">Click Here!</button>
</div>

jQuery Part

You need to include jQuery libraries in the head section of the HTML page. I am using the CDN link for jQuery libraries. You will find it when you download the source code from the given link at the bottom of this tutorial.

First Approach

Here I display each element on the page by clicking on the button. The element is extracted by calculating using modulo operator.

In this approach the element will be shown repeatedly.

$(function(){
	var values = [
		"hi",
		"hello",
		"nice",
		"wonderful"
	];
	var counter = 0, totalElements = values.length;
	$("#btn").on("click", function(){			
		if(totalElements>1) {
			$('#text-center').append(values[counter] + ' ');
			counter = (counter + 1) % totalElements;
		}
	});
});

Second Approach

Here I will also show elements from array one by one on each click on the button but here the element will not be displayed repeatedly.

$(function(){
	var i=0, images = [
		"<img src='first.png' />",
		"<img src='second.png' />",
		"<img src='third.png' />",
		"<img src='kitten.png' />"
	];

	$('#btn').on("click", function(){
		console.log('hi');
		if (i>=images.length) return;
		$('#text-center').append(images[i++]);
	});
});

Final Result

The result is shown here for first approach only.

display array elements jquery

Source Code

Download source code

That’s all. Thank you for reading.

Leave a Comment