Jump to content

randomise ajax for loop


jarvis

Recommended Posts

Hi All,

I have the below script:

<div id="insta"></div>

<script src='//code.jquery.com/jquery-2.2.4.min.js'></script>
<script>
	var token = 'xxx',
    num_photos = 10;
 
$.ajax({
	url: '//api.instagram.com/v1/users/self/media/recent',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){

		for( x in data.data ){
			$('#insta').append('<img src="'+data.data[x].images.low_resolution.url+'"><br/>');
		}
	},
	error: function(data){
		console.log(data);
	}
});
</script>

It retrieves a set number of images from instagram and works a treat!

What I'd like to do, is randomise the results but I can't see how to achieve this. I know it would mean using math.round but can't see how to wrap that in?

Any help is very much appreciated

Link to comment
Share on other sites

So basically, you're looking to randomize the content of "data.data" before it's displayed, correct? If so, I don't know if there's a built-in function available through jQuery or regular JavaScript. However, there are a number of solutions if Google "javascript shuffle array". For example:

https://css-tricks.com/snippets/javascript/shuffle-array/

You would use whatever "shuffle" solution on data.data before the "for( x in data.data ) {" line. 

 

 

Link to comment
Share on other sites

Once again, thanks cyberRobot, that worked a charm!

Here's the final code in case someone else needs a hand:

$.ajax({
	url: '//api.instagram.com/v1/users/self/media/recent',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, count: num_photos},
	success: function(data){
		data.data.sort(function() { return 0.5 - Math.random() });
		for( x in data.data ){
			$('#insta').append('<img src="'+data.data[x].images.low_resolution.url+'"><br/>');
		}
	},
	error: function(data){
		console.log(data);
	}
});

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.