Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image.

However, I am facing an issue with the abrupt transition, causing the background image to flicker. I am looking for a solution to smoothly transition with a fade effect instead.

Here is the code snippet:

function init() {
    let imgDefer = document.querySelectorAll('[data-src]');
    for (let i = 0; i < imgDefer.length; i++) {
        if (imgDefer[i].getAttribute('data-src')) {
            if (imgDefer[i].tagName === 'IMG') {
                imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
            } else {
                let style = "background-image:url({url})";
                imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
            }
        }
    }
}

And here is how the element is structured:

<header class="header header-inverse h-fullscreen p-0 overflow-hidden" data-src="assets/img/headerbg.jpg" style="background-image: url('assets/img/headerbgprev.jpg');"> ... </header>

Answer №1

As recommended, I tackled this issue by initializing an empty div with the set of guidelines below:

header .preview-bg {
    background-image: url(assets/img/headerbgprev.jpg);
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-transition: opacity .3s;
    transition: opacity .3s;
}

Subsequently, I incorporated the following snippet into the deferring script:

$(imgDefer[i]).find('.preview-bg').fadeOut(500);

If there are superior approaches to prevent specific selection issues like this in a way that is applicable to multiple background images simultaneously, suggestions are welcome.

Answer №2

Here is a solution that should meet your needs. It detects elements with a data-src attribute, adds a cover element (such as an image), loads the image specified in the data-src attribute in the background, and once loaded, sets it as the background image and fades out the cover.

While this solution is quite generic, it can be easily customized to suit your specific requirements and preferences :)

function initialize() {
    let imgDeferred = document.querySelectorAll('[data-src]');
    for (let j = 0; j < imgDeferred.length; j++) {
        (function(def) {
          if (def.getAttribute('data-src')) {

              var overlay = new Image();
              overlay.className = "fading-overlay";
              def.appendChild(overlay);

              var preloadImage = new Image();

              setTimeout(function() {
                  preloadImage.src = def.getAttribute('data-src');
              }, Math.random() * 3000);
              
              preloadImage.addEventListener("load", function() {
                def.style.backgroundImage = "url(" + def.getAttribute('data-src') + ")";
                overlay.style.opacity = 0;
              });
          }
        })(imgDeferred[j]);
    }
}

initialize();
div.picture {
  display: inline-block;
  height: 100px;
  margin: 5px;
  width: 150px;
}
div.picture .fading-overlay {
  background-color: rgb(150, 150, 150);
  height: 100px;
  opacity: 1;
  transition: opacity 2s;
  width: 150px;
}
<div class="picture" data-src="https://cmeimg-a.akamaihd.net/cute-article-rcp/cme/cuteness_data/s3fs-public/diy_blog/Why-Are-Some-Cats-More-Vocal-Than-Others.jpg"></div>
<div class="picture" data-src="https://cmeimg-a.akamaihd.net/cute-article-rcp/clsd/getty/f32e47a02653426f8f9dbb1553892225"></div>
<div class="picture" data-src="https://cmeimg-a.akamaihd.net/cute-article-rcp/cme/cuteness_data/s3fs-public/diy_blog/14-tips-that-Could-Extend-Your-Cats-Life.jpg"></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

What could be the reason for the initial response appearing blank?

How can I retrieve all the comments of a post using expressjs with mongodb? I am facing an issue where the first response is always empty. Below is the code snippet: const Post = require("../models/posts"), Comment= require("../model ...

Error occurred while trying to authenticate the user "root" with the password in Linux using NodeJS, Express, and PostgreSQL

Update - Hurrah! It appears I neglected to consult the manual. Following the guidelines exactly for the environmental variables seems to be necessary. Corrected code: # PostgreSQL Database Information PGDATABASE_TEST = user_db PGDATABASE = user_db PGUSER ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

How can you add padding to an HTML page using CSS?

I've been attempting to use padding-bottom:90px; in order to shift Tweets by ‎@StackOverflow (the entire tweets section) downwards on the page. I want to move it further down using the above padding, but it doesn't seem to be working for me. H ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

The data submitted from the form did not successfully get inserted into the database row

Currently, I am working on integrating a new product into my products database using ajax with php and mysql PDO. The form is located in a separate HTML file and gets loaded into a Bootstrap modal when the "add product" button is clicked. Below you can fi ...

Steps to connect my CSS with my HTML in a website hosted on GitHub

I am experiencing an issue with my website hosted on Github pages. It seems to be unable to read the CSS file that I have linked to it. Here is a snippet of my HTML code: <!DOCTYPE html> <link rel="stylesheet" type="text/css" href="https://githu ...

What causes useEffect to be triggered multiple times, even when it is dependent on another useEffect function that is being executed repeatedly?

I have a specific requirement that involves using two useEffect hooks. First useEffect is used to set the latitude and longitude in the state with an empty dependency array. useEffect(() => { navigator.geolocation.getCurrentPosition(geo = ...

The iPage server has encountered a 403 Forbidden Error, preventing

My website is linked with WordPress, but I'm encountering a 403 forbidden error in the sub-menu. Can someone assist me with this issue? I have uploaded a screenshot of the folder in iPage here Additionally, I want my WordPress page to show up correc ...

Is it possible to create repetitive events using loops in jQuery?

When it comes to specificity in coding... $("#ht_1").click(function () { alert("hello"); }); $("#ht_2").click(function () { alert("hello"); }); // here's what I attempted for (i = 1; i <= 2; i++) { $("#ht_" + i).click(function () { ...

"Utilize Ajax to trigger a custom alert message once data is loaded and ready

Is it possible to customize the data object in order to show a JavaScript alert saying "The email address has already been registered!"? Currently, the servlet returns a boolean indicating whether the email is already in the database. $('#emailInput ...

Cautionary alert while displaying a data binding from a controller in AngularJS

Adding a numerical value to the controller: this.myValue = Number(elem.toFixed(2)); Then placing it inside an input form: <input class="my-input" type="number" value={{$ctrl.myValue}} ... > Although the value ...

Exploring the object tag box model and its properties for width and padding in Firefox version 6

Hey there, I've been puzzled by the fact that my Firefox browser seems to be using a different box model for my video embeds compared to Chrome. Even though the same CSS rules are being applied, if the object tag includes attributes like data="whateve ...

Encountering error code 2064 without any clear explanation in sight

Hey, I'm currently facing an issue while uploading values to a MySQL table from Node.js. The error 1064 keeps popping up, indicating that the query is badly formatted. However, I can't seem to pinpoint the exact problem. Here's the query in ...

jinja2.exceptions.TemplateSyntaxError: instead of 'static', a ',' was expected

My current project involves using Flask for Python, and I encountered an error when running the project from PyCharm. The error message points to line 192 in my home.html file: jinja2.exceptions.TemplateSyntaxError: expected token ',', got &ap ...

What is the best way to define a default value for a v-text-field in Vuetify within a Nuxt.js project?

As a beginner with vuejs and nuxtjs, I have been introduced to vuetify at my workplace. I am currently trying to set the default value of 0 for v-text-field fields in the application, but unfortunately, I cannot seem to find this information in the vueti ...

Arrange a pair of div containers side by side on the webpage without the need to alter the existing

Is there a way to align these two div side by side? <div class="main_one"> <div class="number_one">Title A</div> </div> <div class="main_two"> <div class="number_two">Title B</div> </div> <div class=" ...

I am looking to host two Nuxt.js (Vue.js) applications on a single server using PM2

To begin using Nuxt.js, follow these steps: vue init nuxt/express myapp1 vue init nuxt/express myapp2 The structure of my projects is as shown below. /workspace/myapp1 (Nuxt.js application) /workspace/myapp2 (Nuxt.js application) Within my workspace, ...