Dynamic background image that fills the entire webpage, adjusts to different screen sizes, and changes randomly

Currently, I am working on designing a web page with a dynamic background image that adjusts responsively in the browser without distortion. The challenge is to randomly select an image from an array using jQuery.

Unfortunately, my knowledge of jQuery is limited, and I am struggling with this task. Any guidance or assistance would be greatly appreciated!

Here is a snippet of the code I have so far:

<head>
    <title>Test</title>
    <link href="css/css.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="javascript/jquery.js"></script>
</head>
<body>
    <div id="background">   
    </div>  
</body>

This is the CSS code for the background image:

body {
    margin: 0;
}

#background {
    width: 100%;
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-size: cover; 
    background-image: url(backgroundImage)
}

html, body { 
    overflow: none !important; 
    overflow-x: none !important; 
    overflow-y: none !important; 
}

And here is the jQuery script for randomizing the background image:

var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];

var myNumber = Math.floor(Math.random() * 5);

$(document).ready(function () {
    $("background-image").attr('url', picArr[myNumber]);
});

Answer №1

To add some randomness, you can utilize the setTimeout() method.

Furthermore, to alter the background image of the "background" div, simply use a jQuery selector like demonstrated below.

For example:

var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];

$(document).ready(function () {
  setTimeout(function(){
    var myNumber = Math.floor(Math.random() * 5) + 1;

    $("#background").css('background-image', 'url('+picArr[myNumber]+')'); //here
  }, 3000); // milliseconds for frequency of change
});

Answer №2

Did you make a mistake in the selector $("background-image")? Shouldn't it be $("#background")

var images = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg'];

var randomIndex = Math.floor(Math.random() * 5);

$(document).ready(function () {
    $("#background").attr('url', images[randomIndex]); //here
});
#background {
    width: 100%;
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-size: cover; 
    background-image: url(backgroundImage)
}
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
<div id="background">
</div>

Answer №3

It seems like the question has already been answered, but here is my approach:

const imageArray = ['https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg'];

const arrayLength = imageArray.length;

const randomNumber = Math.floor(Math.random() * arrayLength);

console.log(randomNumber);

$(document).ready(function () {
    $("#background").attr('style', 'background-image: url(' + imageArray[randomNumber]) + ')';
});

Styling in CSS:

html, body {
    margin: 0;
    height: 100%;
    min-height: 100%;
}

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

Utilizing Regular Expressions for extracting data from an HTML webpage

Is it possible to extract the response "Here is the solution" from an HTML document using Regular Expression? <b>Previous Query:</b> <b>Here is the answer</b> ...

Using padding and float properties in the a tag of HTML does not result in the expected behavior

I am attempting to display the menu in a left-to-right fashion, however I am encountering issues with using padding and float in HTML. Here is my current code: .main-nav ul li a { padding-right: 15px; float: left; } <div class="main-nav"> &l ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

Conceal navigation button within react-material-ui-carousel

After successfully incorporating the React Material UI carousel, I found it to be quite simple. However, one thing that eluded me was how to hide the buttons and only display them on hover. I tried setting the props navButtonsAlwaysVisible to false, but it ...

When running JavaScript from a .js.erb file, it gets executed while still being visible as plain text

I'm facing an issue with a form inside a popup window. Here's how it looks: <%= form_tag "/controller/action", :method => :get, :remote => true do %> ... <% end %> Within my controller: respond_to do |format| format.js end ...

Which tag should I use, <b> or <mark>, to emphasize important marketing terms within a paragraph?

Trying to emphasize specific keywords in a paragraph of text can be challenging. I'm currently puzzled about the distinction between the <b> and <mark> tags. These words are highlighted because they play a crucial role in marketing, prompt ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Even with a highly lenient Content Security Policy in place, I continue to encounter violation errors

I currently have this meta tag in my HTML document: <meta http-equiv="Content-Security-Policy" content="default-src *;script-src *"> My project uses ParcelJS as a bundler. Everything works smoothly when using the development serv ...

The Jquery code for Fullpage.js is causing unexpected behavior on the HTML page

While following a tutorial at the given link, I encountered an issue. Around the 9:08 mark, the instructor adds some JavaScript and demonstrates that fullpage.js is working. However, when I refresh the page after implementing the new code, it doesn't ...

Is there a way to conceal one column in a row and display only the second column from a medium screen to a small screen using Bootstrap 5?

I am currently working on creating a row with two columns, one being the left_bar column and the other a large image. My goal is to display only the large image (column 2) when the screen size changes from medium to small breakpoints, hiding the left_bar c ...

Proper positioning of popover ensures it does not exceed the boundaries of its parent

In my ngprime table, the header row contains a column field with a popover set to display at the top. However, it is covering the actual field instead of appearing above it. This issue arises because the popover cannot display outside of its parent div, ca ...

Enhancing the efficiency of nested ajax calls loop

Disclaimer: While the final result is successful, I am struggling to comprehend the sequence in which a loop of nested ajax calls operates. Essentially, I have two ajax calls that fetch data from an external API using curl GET requests. They both rely on ...

Ensuring that links are functional across all directory levels: a comprehensive guide

Looking at the image included here, you can see a preview of the website I'm currently building. The plan is to have individual pages for each machine in the company's lineup. Since the navigation bar and menu will be consistent across the entire ...

Draggable Elements in jQuery for Scrolling Windows

When using jquery ui sortable, everything works fine without window scroll and my items stay contained. However, if I start sorting the items after scrolling the window, they jump to the same height as the window scroll and no longer stick to my mouse poin ...

Using CasperJS, learn how to effectively utilize the jQuery find() function

I'm looking to implement something similar to Cabybara within a function in CasperJS. My goal is to select parent divs and extract text from their child elements. Here's an example of what I want: $('div.education').find('h4&apos ...

Customize Input Values by Selecting an Option with jQuery-UI Autocomplete

Hello there, I am a newcomer to java-script and could really use some help. My goal is to have the data in the country field automatically populated when a user enters data into the city field. I have an xml file: <ROWSET> <ROW> <city>&l ...

Implementing gridlines on a webpage using HTML and JavaScript to mimic the grid layout found in Visual Studios

Currently, I have a grid snap function in place, however, I am looking to add light grey lines horizontally and vertically on my Designing application. The goal is to achieve a similar aesthetic to Visual Studios' form designing feature. Utilizing so ...

Combing external JavaScript with React functionality

Hey there, I've been working on merging two projects that I came across recently: https://github.com/danxfisher/MeetEasier and this awesome page https://tympanus.net/Development/Interactive3DMallMap/ After making some changes in the MeetEasier React ...

Trouble with flex wrap in my design template using Material UI

How can I create a responsive template using flexbox wrapping method? <Box sx={{ padding: 0, margin: 0, listStyle: "none", display: "flex", flexFlow: ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...