Skip to content

Instantly share code, notes, and snippets.

@aloncarmel
Created August 20, 2013 13:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save aloncarmel/6281514 to your computer and use it in GitHub Desktop.
Save aloncarmel/6281514 to your computer and use it in GitHub Desktop.
Grab a random background from unsplash.com and apply to a div.
function GetRandomBackground()
{
var url = 'http://unsplash.com/rss';
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
var min = 0;
var max = json.responseData.feed.entries.length;
// and the formula is:
var random = Math.floor(Math.random() * (max - min + 1)) + min;
var str = json.responseData.feed.entries[random].content;
var regex = /<img.*?src="(.*?)"/;
var src = regex.exec(str)[1];
$('#selector').css('background-image','url('+src+')');
}
});
}
@aloncarmel
Copy link
Author

Technically its possible to replace the url with http://blog.instagram.com/tagged/photo_feature/rss and get featured images from instagram :)

@TheAlp
Copy link

TheAlp commented Jul 25, 2015

I'm trying to figure out how to use this to make the background of my header a random image from my rss feed but I can't seem to get it to work. I'm a bit new to this so could you perhaps explain a bit about how to use it or send me in the right direction?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment