implement CSS styles within a JavaScript function

I am trying to change the background every second with the following code, but I am having trouble including CSS properties like centering, covering, and positioning the image properly. How can I modify this function to incorporate these settings for the background images in the CSS?

$(function() {
  var body = $('body');
  var backgrounds = ['url(http://static.jsbin.com/images/jsbin_static.png)', 'url(http://static.jsbin.com/images/popout.png)'];
var current = 0;

function displayNextBackground() {
  body.css(
   'background',
    backgrounds[current = ++current % backgrounds.length]
 );
 setTimeout(displayNextBackground, 1000);
 }
 setTimeout(displayNextBackground, 1000);
   body.css('background', backgrounds[0]);
 });

Answer №1

There is a property in elements called style.backgroundImage that allows you to control the background image. To change the background image using javascript, use the following code:

document.querySelector('body').style.backgroundImage = "url('yoururl')";

Answer №2

Remember, the background property can accept shorthand values for all of its properties, allowing you to simplify your code:

background: url(image);
background: url(image) center;
background: url(image) center no-repeat;
background: #000 url(image) center no-repeat;
and so on.

You can achieve the same result using jQuery in a similar manner:

$(element)
   .css('background','url(image)')
   .css('background','url(image) center')
   .css('background','url(image) center no-repeat')
   .css('background','#000 url(image) center no-repeat')
   and so forth

Answer №3

One way to achieve this effect is by using only CSS:

@keyframes backgrounds {
  0% {
    background-image: url(http://static.jsbin.com/images/jsbin_static.png);
  }
  
  50% {
    background-image: url(http://static.jsbin.com/images/popout.png);
  }
}

.rotating-background {
  width: 250px;
  height: 250px;
  background-position: center;
  background-repeat: no-repeat;
  animation: backgrounds 2s steps(1, end) infinite;
}
<div class="rotating-background"></div>

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

Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, ...

Tips for passing a URL variable into an Ajax script to prefill a form input in a search field

I have a website with a search feature that dynamically queries a database as you type in the search field, similar to Google's search suggestions. This functionality is achieved through AJAX. As the results appear on the page while you enter your se ...

What could be the reason for the excess white space at the top and bottom of the page?

Once I implemented a new div class to incorporate a background image, the top, bottom, and side menus on my page suddenly turned white. style.css #boundless{ background-image:url('http://thehypebr.com/wp-content/uploads/2010/09/boundless-sem-branc ...

Arranging the elements in my footer for optimal display

My footer layout expands and the lists in each column become misaligned as I add more links to it. I want to make sure that the lists for each column are aligned horizontally on the same row, with the title of each column also in the same row. levi | ...

Why React Native's array.map function fails to calculate the sum of a state

I am currently developing a COVID-19 data app for a school project, and I am struggling to sum the total number of tests and positive results from an API. Below is the snippet of code that I am using: function GetDataApi() { if(data !== null) { const ...

Error: Discord Bot is unable to locate module './commands/ban.js'

Here is my code snippet: require('dotenv').config(); const fs = require('fs'); const Discord = require('discord.js'); const { error } = require('console'); const client = new Discord.Client(); client.commands = new D ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Adjusting the height of an IFRAME on the fly

One solution to dynamically fix the height issue of Google Trend charts is by modifying the code output. An example of this can be seen in the code snippet below: <iframe width="600" height="320" src="http://www.google.com/trends/fetchComponent?hl=en-U ...

Extracting live content from a website within a native Webview

Running an eCommerce website along with a simple mobile app for both iOS and Android that features a basic tab bar menu, including icons like a shopping cart, profile, refresh button, etc., as well as a Webview to display the website content. The App' ...

Ways to customize the default countdown timer

I came across this amazing project at https://codepen.io/mattlitzinger/pen/ysowF. While the project is wonderful, I am looking to make some modifications to the code, specifically targeting a specific date. Here is the JavaScript code snippet: var tar ...

What could be the reason my PHP file load is not functioning properly?

I'm having trouble figuring out why this code isn't functioning correctly. The result I'm getting from load_docs_2.php is: Array ( ) Incorrect file type. This issue is occurring on a XAMPP server. The HTML code in question is: <form id= ...

Bootstrap 4's hamburger icon in the navbar toggler displaying only two lines, rather than three

I have created a navbar using Bootstrap 4. Although the navbar is functional, I am facing an issue that I have not been able to resolve on my own. When collapsed, the hamburger icon only displays two lines instead of three. I suspect that the problem lie ...

Determine whether a URL has already been encoded using the encodeURI function

Attempting to accomplish this task in VBScript/JScript to prevent re-encoding. Is it necessary to check for the presence of "%" ? Are there other purposes for "%" in URLs? Thank you. Edit: Oh, perhaps the original encoding method wasn't encodeURI ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

Ways to resolve the issue of missing data display in Angular when working with the nz-table

Below is the code snippet: <nz-table #listTable nzSize="middle" [nzData]="data"> <thead> <tr> <th nzShowExpand></th> <th>Location</th> <th>Device</th> ...

Using Vue.js, separate the values that are separated by commas

I am looking to extract values from a string and store them in an array for use in displaying values in a dropdown format within Vuejs String str = "abc,123,676,uuu". Once I have iterated through the values <li v-for = "value i ...

Tips for navigating through the search results on Google Maps with Selenium

I am facing an issue where I am only able to retrieve the first 7 results out of 20 using the given code. It seems that I am unable to scroll to the bottom to access all the results. Can someone please advise on additional steps required to achieve the d ...

Comprehending the inner workings of the reduce() method

After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce ...

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

Uploading files using Multipart/form-data in Node.js and Express.js

With the removal of express.multipart from the Express 4.x library, what approach would be most effective for managing file uploads in expressjs? ...