Refresh the page to see a variety of new images loaded each time

Incorporated into my HTML file is a concise script:

$(document).ready(function() {

    var rand = Math.floor((Math.random()*3)+1) //generates random number between 1 and 3

    $("body").css({ "background": "url(image" + rand + ".jpg)",
                    "background-size": "100% 100%",
                    "background-repeat": "no-repeat"
                 });
});

The concept behind this script is to randomly display one of three images (image1.jpg, image2.jpg, or image3.jpg) hosted on the server when the page loads.

Is there a more effective approach for achieving this?

PS - This situation bears similarities to the GitHub Notifications page. After viewing all notifications, each time you refresh the page, a new version of the octocat appears to welcome you :)

Answer №1

One option is to transfer:

"background-size": "100% 100%",
"background-repeat": "no-repeat"

Into

body {
    background-size: 100% 100%;
    background-repeat: no-repeat;
}

Since this code remains constant every time it is used.

If you are dealing with a randomly selected image, you will need some JavaScript on the server side in order to inform body about which background image to display each time.

The number of images stored on the server is not as important as ensuring there is only one HTTP request needed to retrieve the image.

Answer №2

Enhance its dynamism.

<div id="imgselection">
    <img alt="test" src="https://www.example.com/slide1.jpg"/>
    <img alt="test" src="https://www.example.com/slide2.jpg"/>
    <img alt="test" src="https://www.example.com/slide3.jpg"/>
    <img alt="test" src="https://www.example.com/slide4.jpg"/>
</div>

<script>
    $(document).ready(function (jQuery) {
        var images = Array();
        var indexImages = Array();
        jQuery("#imgselection img").each(function (index) {
            images.push(jQuery(this).attr('src'));
            indexImages.push(index);
            jQuery(this).hide();
        });
        var selectedImage = images[Math.floor(Math.random() * images.length)];
        jQuery('body').css('background-image', 'url(' + selectedImage + ')');
      // // OR Display a single image
      //  var selectedIndexImage = indexImages[Math.floor(Math.random() * indexImages.length)];
      //  jQuery('#imgselection img').eq(selectedIndexImage).show();
    });
</script>

Answer №3

My recommendation is to opt for using window.onload over DOM ready.

I am confident that by first generating rand and preloading the image before triggering window.onload, the image will load faster:

By the time window.onload is triggered, the browser cache will ensure swift loading of the image which was preloaded.

var rand = Math.floor((Math.random()*4)+1);
var imgPreload = new Image();
imgPreload.src = 'image' + rand + '.jpg';
$(window).on('load', function() {
    $("body").css({ "background": "url(image" + rand + ".jpg)",
                   "background-size": "100% 100%",
                   "background-repeat": "no-repeat"
                  });
});

Answer №4

One alternative method involves creating a script that generates and serves an image randomly, allowing it to function as a separate module without the need for integration into the primary JavaScript/jQuery code. It's essential to ensure that the browser does not cache these images.

Here is an example:

body {
    background-image: url(randomImageGenerator.js);
    background-repeat: no-repeat;
    background-size: cover;
}

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

An AJAX request can affect the functionality of an if/else statement

I am currently working on integrating AJAX functionality into my code for a 'like' button. I have both the 'Like' and 'Dislike' buttons displayed on the screen. An AJAX request is made to check my database, and depending on th ...

A guide on accessing every element within a "div" tag that begins with a specified text

In my HTML document, there is a div element present. I am looking to retrieve all elements within this specific div that have id attributes beginning with a certain string (e.g. "q17_"). Is it possible to accomplish this task using JavaScript? If necess ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Guide to redirecting an old tab to a new one after submitting

When submitting a form in a new tab, I use the following code: <form action="xxx.php" target="_blank" method="post"> However, the old tab remains on the form and I want it to redirect to a different page after submission. Appreciate any help! ...

Make the div larger if the child element exceeds 100%

Trying to ensure that the width of the header matches the intrinsic width of the content as divs are meant to occupy the full width. Attempted applying overflow:auto to html,body,header https://codesandbox.io/s/xrn9q6ojxw <head> <tit ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...

Executing an ASP.NET button click event handler within an update panel can trigger twice unexpectedly when using jQuery to simulate an Enter

I have encountered an issue on my webpage <asp:TextBox Text="" ID="txtEmailOApodo" MaxLength="70" runat="server" Width="250px" Style="height: 25px"></asp:TextBox> <asp:TextBox Text="" ID="txtContrasena" MaxLength="50" TextMode=" ...

Seeking guidance on Ajax .... in need of clarification

Could someone provide an explanation for this code snippet: const greeting = 'hi'; $.ajax({ type: "POST", url: "check.php", data: "greeting="+greeting, success: function(response){ alert( "Response received from server: " + resp ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

How can you efficiently send JSON data from Ajax to a Servlet in a Java environment?

I am encountering a perplexing issue with sending data from my jQuery script to a servlet using AJAX. The strange part is that when I set the contentType to application/json, all values on the server side turn out to be null. However, if I remove it, the s ...

Sharing data between functions in jQuery AJAX promises

Struggling to define a variable in one promise method and use it in another? Here's the scenario: Take a look at this code snippet: $.getJSON('some/file/') .done(function(response) { var bar = response; }) .always(function() { // N ...

Unable to save a URL link in MySQL database using JSON and PHP

I am seeking some insightful advice regarding my college assignment. This time around, I have to create yearbooks using Phonegap and it's my first experience working with AJAX, JSON, and JQuery Mobile. Instead of uploading an image directly into the ...

Tips for deleting a button from a DataTable file upload feature

I currently have Datatable set up to upload images using the code snippet below: { label: "Images:", name: "files[].id", type: "uploadMany", display: function ( fileId, counter ) { re ...

Creating a Sticky Table Header with Dynamic Height in React using Material-UI

I am currently utilizing the Material-UI library in React to present a table on my webpage. My goal is to have a sticky header on the table without specifying a fixed height, allowing it to scroll along with the page. However, the code snippet provided doe ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

Display the user's chosen background image as the backdrop for my activity

As I've been exploring various corners of the internet, I've come across a potential technique for accessing the user's background from within my activity. I've brainstormed a couple of ideas (even though they might seem silly, just to ...

Press the jQuery button to reset all input fields

I have created a table with input fields where class teachers can store their students' data for the principal to review. Each row in the table contains an update and reset button, allowing teachers to save or clear the information entered in the fiel ...

What is the process for receiving input from a text field on a Django webpage and subsequently updating an SQL table with the submitted information?

I am currently developing a website with a specific purpose of managing inactive Tableau workbooks. By logging into the site, users will be able to view their old workbooks and determine which ones to retain. This will be achieved by collecting simple tex ...

Scripts fail to load randomly due to RequireJs

I have obtained an HTML template from a platform like Themeforest, which came with numerous jQuery plugins and a main.js file where all these plugins are initialized and configured for the template. I am now in the process of developing an AngularJS applic ...