The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time.

var act = true;
setInterval(function(){
  if (act) {
    $("div").addClass("back2")
    $("div").removeClass("back")
    act = false
  } else {
    $("div").addClass("back")
    $("div").removeClass("back2")
    act = true
  }
}, 10000)
.back{
  width:100px;
  height:100px;
  background-image:url("https://www.skoobe.de/static/v/7b2334ac8a86ab5d764bc6e94df87df4aa5b4e2adc78c783e73ae2cbaf613745.jpg");
  display:block;
  transition: .5s ;
}

.back2{
  width:100px;
  height:100px;
  background-image:url("https://www.skoobe.de/static/v/a5c0d3825217f88c4c893e7b630c4f1c5eb4c9bec834e1112383614270b5d583.jpg");
  display:block;
  transition: .5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="c">tz</div>

Answer №1

background-image is considered a non-animatable property according to the list provided on the mozilla dev page at this link: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

One workaround is to have two divs with separate background images overlapping each other, and then manipulate their transparency to create a blending effect.

To better illustrate this concept, I created a fiddle showing how it can be implemented:

https://jsfiddle.net/Lpduw3mq/

// select elements
var firstDiv = $("#first")
var secondDiv = $("#second")

// Toggle backgrounds
var action = true;
setInterval(function(){
  if (action) {
    firstDiv.addClass("transparent")
    secondDiv.removeClass("transparent")
    action = false
  } else {
    firstDiv.removeClass("transparent")
    secondDiv.addClass("transparent")
    action = true
  }
}, 5000)
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

.base {
  position: absolute;
  top: 0;
  left: 0;
}

.back {
  width: 100px;
  height: 100px;
  background-image: url("https://www.skoobe.de/static/v/7b2334ac8a86ab5d764bc6e94df87df4aa5b4e2adc78c783e73ae2cbaf613745.jpg");
  display: block;
  opacity: 1;
  transition: opacity 0.5s;
}

.back2 {
  width: 100px;
  height: 100px;
  background-image: url("https://www.skoobe.de/static/v/a5c0d3825217f88c4c893e7b630c4f1c5eb4c9bec834e1112383614270b5d583.jpg");
  display: block;
  opacity: 1;
  transition: opacity 0.5s;
}

.transparent {
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" class="base back"></div>
<div id="second" class="base back2 transparent"></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

CSS: Floating navigation bar that becomes fixed upon reaching the top of the page

Looking for a creative approach to achieve the following: An innovative navigation bar that initially appears on a page regularly but then becomes fixed at the top as I scroll down. An alternative perspective: imagine a navigation bar that starts off unf ...

What are some practical ways to incorporate jQuery OOP into a live website?

If you have any suggestions for improving my implementation or if you'd like to share your ideas, please feel free to do so. //* global variable *// //I placed all the variables inside $('body'); $base_url = $('body').data('b ...

Removing the restriction on maximum width to 100% and allowing for automatic height adjustment

Within my project, I have implemented a CSS technique where all images within a container are set with the attributes max-width: 100%; and height: auto;. This is done to ensure that images scale down appropriately when the viewport and container size decre ...

What's the best way to display my slider exclusively on the homepage?

Hello, I am experiencing an issue with my slider. I would like to display the slider only on the home page and not on any other sub-pages. Is there a way to achieve this? Below is the code that I am using: <script> $( ...

The document could not be read by Jackson due to an unrecognized token 'contactForm', which was expecting either 'true', 'false', or 'null'

When attempting to send a POST request using JQuery to a Spring Controller, an error keeps popping up from JQuery. An issue arises with the following message: "Could not read document: Unrecognized token 'contactForm': was expecting ('true& ...

Safeguard your contact information on the screen

On my classified website, I have concerns about the contact numbers being displayed as plain text in the product details page. This makes them visible to search engines. Is there a way to protect or display phone numbers as images to keep them hidden fro ...

Detecting mistakes on the server end

Fetching data in JSON format from my server to display as a table. $('#queryFrom').ajaxForm({ dataType: 'json', beforeSubmit: showRequest, / ...

Displaying a jquery delay prior to revealing the content

I need help figuring out how to temporarily hide something using jQuery. Unfortunately, the code I've written doesn't seem to be functioning correctly. Could it be that the delay time is too short? $('#mainForm').hide().delay(8000).sh ...

Encountering an error that states "this.push is not a function" when trying to select the 2nd or 3rd option

My goal is to extract elements from a drop-down menu and populate a list box based on the selection. The selected value from one list box should then be transferred to another list box, specifically from Available to Selected. However, while selecting Deve ...

Bootstrap 5's ScrollSpy functionality seems to be malfunctioning

I attempted to implement the scroll-spy feature of Bootstrap 5 in order to highlight the corresponding navbar item as active while scrolling through different sections of my HTML page. However, I encountered an issue where the navigation-link item would be ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...

Integrate geographic data in GeoJSON format into a Leaflet map by using the Django template

In my Django view, I am fetching results of an SQL query and rendering it on the index.html page of my web map. The POST request successfully returns the acreage calculated from the SQL query to the page. I am also attempting to display the geojson data fr ...

What is the best way to adjust column sizes, setting one with a minimum width while allowing the other to expand to accommodate its content?

In the process of creating a user interface, I have included clickable cards that reveal a detailed panel when clicked. The detail panel is set to a minimum width of 900px and should adjust to the remaining space between the cards and itself. The column ...

Techniques for retrieving elements from HTML using jQuery

I'm developing a feature that allows users to add videos to playlists by clicking on a link in a popover. The challenge I'm facing is extracting the video_id and the selected playlist when the user interacts with the popover. Any tips on how to a ...

Limit access to the webpage to only one user at any given time

There are two users: X and Y, and one page called Page Z. In order to access Page Z, there is a link available. If Page Z is already open in user X's browser, I need the link to be disabled and deny access to user Y. What is the best way to achieve ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

Is there a way to set the background of a HTML5 page as an image with a clickable link?

Lately, I've been working on a webpage dedicated to educating people about Mars. I wanted to spice things up by using an image as the background for my HTML5 page instead of the usual plain white color. However, just inserting a .jpg link didn't ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

Implementing CSS styles based on the count of elements

Within my react js project There is a particular block that may contain either one or two elements, depending on the runtime conditions. For instance: Scenario 1: (two groups are present) <div class='menu-list'> <div class='g ...