Jump to content

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
https://forums.phpfreaks.com/topic/307524-randomise-ajax-for-loop/
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. 

 

 

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);
	}
});

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.