Is there a way to incorporate a background image fadeIn effect for ul using CSS3?

I have a list on my webpage where each item is displayed with a CSS3 rotate animation. After the animation finishes, I want to set a background image with a FadeIn effect.

To achieve this, I created a "addbg" class for the ul element like so:

ul.addbg{
    background: transparent url(../img/circle-line.png) no-repeat 49% 94px;
    -webkit-transition: background 5.6s;  
    -moz-transition: background 5.6s;  
    -o-transition: background 5.6s;  
    transition: background 5.6s; 
}

However, nothing seems to be happening. How can I make this work?

Here is my current ul structure:

<ul class="addbg">
    <li>
        <span>Text1</span>
     </li>
    <li>
        <span>Text2</span>
    </li>
    <li>
        <span>Text3</span>
    </li>
    <li>
        <span>Text4</span>
    </li>
</ul>

Answer №1

It's not possible to transition the background-image property directly, but you can achieve a similar effect by setting the background-image to a :after pseudo-element and transitioning its opacity instead.

Here is a simple example:

#image {
  position: relative;
  width: 300px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
#image:after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: url(http://www.lorempixel.com/300/100);
  opacity: 0;
  transition: opacity 1s;
  z-index: -1;
}
#image:hover:after {
  opacity: 1;
}
<div id="image">Some Content</div>


If you prefer a delay instead of using :hover, you can define @keyframes and incorporate a delay (e.g., 3s in the example below) to the animation. Afterwards, you can use JavaScript to set the opacity of #image:after to 1 once the animation has finished.

animation: fadeIn 1s 1 3s - Here, fadeIn represents the animation-name, 1s is the animation-duration, 1 is the animation-iteration, and 3s is the animation-delay.

var img = document.getElementById('image');
var event = ['webkitAnimationEnd', 'animationend'];

for (i = 0; i < event.length; i++) {
  img.addEventListener(event[i], function() {
    var ss = document.styleSheets;
    for (j = 0; j < ss.length; j++) {
      var rules = ss[j];
      for (k = 0; k < rules.cssRules.length; k++) {
        var r = rules.cssRules[k];
        if (r.selectorText == "#image::after" || r.selectorText == "#image:after") {
          r.style.opacity = 1;
        }
      }
    }
  });
}
#image {
  position: relative;
  width: 300px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
#image:after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: url(http://www.lorempixel.com/300/100);
  -webkit-animation: fadeIn 1s 1 3s;
  animation: fadeIn 1s 1 3s;
  z-index: -1;
  opacity: 0;
}
@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div id="image">Some Content</div>


Another approach would be to create a pure JavaScript animation using setTimeout() for the delay and setInterval() for the animation, without relying on transition or @keyframes.

var ss = document.styleSheets;
for (i = 0; i < ss.length; i++) {
  var rules = ss[i];
  for (j = 0; j < rules.cssRules.length; j++) {
    var r = rules.cssRules[j];
    if (r.selectorText == "#image::after" || r.selectorText == "#image:after") {
      var op = 0;
      setTimeout(function() {
        var fadeIn = setInterval(function() {
          r.style.opacity = op;
          op += 0.005;
          if (op > 1) {
            clearTimeout(fadeIn);
          }
        }, 7)
      }, 3000)
    }
  }
}
#image {
  position: relative;
  width: 300px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
#image:after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: url(http://www.lorempixel.com/300/100);
  z-index: -1;
  opacity: 0;
}
<div id="image">Some Content</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

The malfunctioning of JqueryUI icon with ui-state-error within a dialog

Currently, I am facing an issue with displaying a ninput and two spans containing jQuery UI icons in a jQuery UI dialog. The problem arises specifically when applying the ui-state-error to one of the spans. Interestingly, outside the dialog, the icons dis ...

Using innerHTML within a JS function causes the class to malfunction

I want to embed HTML code using innerHTML, which will add an input with the class .flatpickr-date. let newInput = '<input type="text" class="flatpickr-date">' document.getElementById('id').innerHTML = newInput; In my JavaScript ...

Calculating the subtotal amount using Vue.js is a straightforward process

My Vue.js project functions as a shopping cart, and I am looking to calculate the subtotal for each product row. Here is an excerpt of my HTML code: <div id="app"> <table border="1"> <thead> <tr> <th>#</th ...

JavaScript - unable to view updated information without refreshing page

I am currently developing a Single Page Application (SPA) using Rails for the backend and JavaScript for the frontend. When I submit the initial form to create a Resource, it shows up on the page immediately upon pressing the submit button. However, when I ...

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

MUI Autocomplete is failing to update the value when onChange event is triggered

I have successfully fetched autocomplete options from an API and it displays the pre-selected options from the API. However, I am encountering an issue where I am unable to delete or add a value (category) once selected. For an online demo, you can check ...

I am experiencing an issue where tapping on the Status Bar in MobileSafari is not functioning correctly on a specific

I am struggling to troubleshoot this problem with no success so far. The HTML5 JavaScript library I'm developing has a test page that can display a large amount of output by piping console.log and exceptions into the DOM for easy inspection on mobile ...

Using Javascript to save a numeric value and accessing it on a different webpage

I'm encountering an issue with a specific feature on my website. I want users to click on a hyperlink that will redirect them to an application form page. The challenge is ensuring that the reference number (a 5-digit code displayed as a header) is st ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

"Combining jQuery and JavaScript to handle form submissions in un

What happens when you combine the Javascript onSubmit handler and jQuery submit handler? <form action="" method="post" onSubmit="myJavascriptHandler();"> <input type="submit" /> </form> <script type="text/javascript"> $("form") ...

Tips for updating multiple fields in Prisma ORM

Is there a way to upsert multiple fields in Prisma ORM using just one query? I'm looking for a solution that allows me to upsert all fields at once, without having to do it individually. Is this possible? ...

Ever wonder what goes on behind the scenes when you press a button before the Javascript method is carried out

My web application is built using ASP.NET MVC 4, jQuery, and Telerik's Kendo controls. Within my webpage, I have the following code snippet: <input id="cmdSaveToFile" title="Save To File" class="button" type="button" value="Save To File" onclick= ...

Execute an AJAX request and dynamically update the page when the button is clicked simultaneously

Hello everyone, I'm a beginner in ajax and I'm encountering an issue with executing JavaScript when a button is clicked. What I'm trying to achieve is, when the button is clicked, I want to run an ajax function to call a PHP script for query ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...

Obtain the result returned from a JSON using jQuery's Ajax GET

Can you help me figure out how to retrieve the JSON result of a PHP function in an Ajax request for verification purposes in onSucces? public function checkEmailValidityAction() { $is_valid = true; $is_duplicate = false; $email_reset = false ...

Adjusting the width of a Material UI drawer: Tips and tricks

Currently, I am working on implementing the Material UI drawer and anchoring it to the top of my page. It is functioning correctly, however, I am encountering an issue where I am unable to adjust the width of the drawer. Despite trying to update the width ...

Passing a global variable as an argument to a jQuery function is not allowed

I am attempting to display local weather information using an API. The API URL is generated based on the user's current position. var lat, lon = null; var key = "mykey"; var api = ""; function setApi(position){ lat = Math.round(position.coords.lati ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...