Show a new GIF on each page visit or page reload

时间:2016-04-12 00:38:34

标签: javascript arrays json gif giphy

I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!

Here is the function I'm using to query data

function weather(position) {
  var apiKey = '';
  var url = '';
  var data;
  // console.log(position);
  $.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {

    $('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
    $('.js-current-item2').html(data.currently.summary);

    gif(data.currently.icon)
    city(position.coords.latitude + "," + position.coords.longitude)

  });
}

And here is the function for pulling images from GIPHY

function gif(status) {
  var apiKey = '';
  var url = 'http://api.giphy.com/v1/gifs/search?q=';
  var query = status;
  $.getJSON(url + query + apiKey, function(data) {
    $('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
  });
}

1 个答案:

答案 0 :(得分:1)

在设置图像时,在函数gif(status)中选择数据数组中的随机值而不是固定的

更改

$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');

var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');