Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  47] [ 5]  / answers: 1 / hits: 47895  / 9 Years ago, wed, september 16, 2015, 12:00:00

I have this idea for my website that every time you visit the page, the background will be different. I want to get literally any picture from Google images and place it as my website's background using Javascript.



Basically every time you refresh the page a script will fetch a random picture from Google images and place it as the background or maybe at least download the picture.



How should I do this, or is it even possible?


More From » html

 Answers
13

It can be done via Google Images though much customization is required so the script behaves as you intended (including setting up a delay to handle rate-limiting; Google has a rate-limit of 64 items per search request over API) here is a basic example using Google Images api:



<html>
<head>
<title></title>
<script src=https://www.google.com/jsapi></script>
<script type=text/javascript>
google.load('search', '1');
google.setOnLoadCallback(OnLoad);
var search;

//i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
var keyword = 'mountains';

function OnLoad()
{
search = new google.search.ImageSearch();

search.setSearchCompleteCallback(this, searchComplete, null);

search.execute(keyword);
}

function searchComplete()
{
if (search.results && search.results.length > 0)
{
var rnd = Math.floor(Math.random() * search.results.length);

//you will probably use jQuery and something like: $('body').css('background-image', url(' + search.results[rnd]['url'] + '));
document.body.style.backgroundImage = url(' + search.results[rnd]['url'] + ');
}
}
</script>
</head>
<body>

</body>
</html>


However may I suggest instead: Random images from flickr, here is another basic code for that (sky is the limit):



<html>
<head>
<title></title>
<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js></script>
<script type=text/javascript>

var keyword = mountains;

$(document).ready(function(){

$.getJSON(http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?,
{
tags: keyword,
tagmode: any,
format: json
},
function(data) {
var rnd = Math.floor(Math.random() * data.items.length);

var image_src = data.items[rnd]['media']['m'].replace(_m, _b);

$('body').css('background-image', url(' + image_src + '));

});

});
</script>
</head>
<body>

</body>
</html>

[#65041] Monday, September 14, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxd

Total Points: 568
Total Questions: 100
Total Answers: 101

Location: Serbia
Member since Tue, Jul 26, 2022
2 Years ago
;