Introduction

We will see how to display elements one by one from an array using jQuery. The below example shows how to achieve it using jQuery. We have a button here 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.

Example with Code

HTML Part

In our HTML code snippets we have just one div with button for clicking on it.

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

jQuery Part

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

First Approach

Here we show each element on clicking on the button. We extract the element 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 also we will show elements from array one by one on each click on the button but here the element will not be repeatedly displayed.

$(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.

display array elements jquery

Source Code

You can download source code.

That’s all. Thank you for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *