-
-
Save abruneau/d59803ffffa8e8c20bda7e0e274c281e to your computer and use it in GitHub Desktop.
Grab a random background from unsplash.com and apply to a div.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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+')'); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment