Display a different GIF every time a page is visited or refreshed

I am incorporating the GIPHY API to showcase an image based on a query. The current code I have pulls the image successfully, but there is a recurring issue where the same GIF displays each time the website is visited until the query is altered. My aim is for the GIF to refresh after every visit or page reload to exhibit a new random image from the array, even if the query remains unchanged. As a newcomer to JavaScript, I am uncertain of how to tackle this issue, so any assistance would be greatly valued!

Below is the function I utilize to retrieve data:

function weather(position) {
  var apiKey = '';
  var url = '';
  var data;
  
  $.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)

  });
}

Here is the function responsible for retrieving 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 + ')');
  });
}

Answer №1

When you're working with the gif(status) function, consider selecting a random value from the data array instead of using a fixed value.

Make this adjustment:

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

Change it to:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

Utilizing Bresenham's line drawing algorithm for showcasing box contours

I am seeking a similar behavior to what is demonstrated on , but with some modifications to the boxes: div { display: inline-block; width: 100px; height: 100px; border: 1px solid black; cursor: pointer; } div.selected, div:hover { backgroun ...

Using Node.js to display the outcome of an SQL query

I have been attempting to execute a select query from the database and display the results. However, although I can see the result in the console, it does not appear on the index page as expected. Additionally, there seems to be an issue with the way the r ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

Angular - What is the best way to simulate an HTTP request in testing?

Although I currently have a basic code that triggers an actual HTTP request : @Component({ selector: 'my-app', template: ` <div> <h2>Hello {{person?.id}}</h2> </div> `, }) export class App { name:str ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Able to retrieve data from a JSON API

Trying to retrieve information from BayFiles.net via their API. The API call URL is: Encountering this error: 07-04 13:54:39.525: E/log_tag(588): Error parsing data org.json.JSONException: Value at error of type java.lang.String cannot be converted to ...

Assign object properties to a constant variable while validating the values

When receiving the features object, I am assigning its values to constants based on their properties. const { featureCode, featureSubType, contentId, price, family: { relationCountsConfig: { motherCount, fatherCount, childrenCount }, max ...

"Enhance your data management with Laravel and Vue.js by incorporating the powerful Matfish Vue-Table

Currently, I am utilizing matfish-vue-table2 along with server-side implementation. Below is my Laravel controller where I am able to retrieve the JSON response from the 'api/articles' URL: public function index() { $articles = Article::orde ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Bug in Vega-Lite heatmap rendering when using a multi-line calculated field

I recently created a simple heatmap using a minimal example here and everything looked fine at first. However, I noticed that many labels were too long and caused issues with the plot. To address this, I decided to use the transform {"calculate" ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Having trouble retrieving data from getters in the Vue store while inside a template

Within my component, I have set up computed properties that are supposed to display text for blopp and blipp. However, while blopp is working fine, blipp is not showing anything. The end goal is to have blipp generate a list of strings from the store state ...

Filtering JSON-RPC responses with multiple potential values using jq

Struggling to filter out jq output in order to display only the result or error message from a json-rpc response. For instance, here is an example of the response: Normal: { "result": "0001", "id": 1, "jsonrpc": "2.0" } Error: { "error": { ...

Real-time data and dynamic checkbox functionality in AngularJS

I am working on an onclick function that involves data stored in objects. $scope.messages = [ {"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}, ]; $scope.selection = { ids: {} }; $scope.sendMe = function(message) { //send the data with `id` and ...

Converting a dictionary with Arabic characters to JSON utilizing the json.dumps function

I am working with a dictionary that contains Arabic words such as data = [{'name': 'آدَم'}, {'name': 'آزَر'}] print(json.dumps(data), file=open('data.json', 'a', encoding="utf-8")) When ...

Leveraging the socket.io and express modules independently of npm

I am currently developing a project for an embedded Linux system using busybox created with buildroot. I'm intrigued by the idea of utilizing node.js modules such as socket.io and express without needing to depend on the installation or execution of n ...