Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opacity so that the image beneath it becomes visible without affecting the content inside the overlaying div.

However, my current implementation is far from ideal: https://jsfiddle.net/n7t2xmha/3/

  • The animation lacks smoothness
  • The opacity adjustment is inaccurate
  • The text doesn't remain solid

Code:

<div class="outerdiv">
    <div class="innerdiv">
    </div>
    <p>
        content - should remain solid white
    </p>
</div>

.outerdiv {
    background-color: black;
    position: relative;
    display: block;
    height: 500px;
    width: 500px;
    color: white;
    -moz-transition: all 1s linear;
    -o-transition: all 1s linear;
    -webkit-transition: all 1s linear;
    transition: all 1s linear;
}

.outerdiv-opaque {
    opacity: 0.9 !important;
}

.innerdiv {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index=-1;
}

JS

var innerDiv = $('.innerdiv');
setTimeout(function() {
    innerDiv.css('background-image', 'url(https://i.sstatic.net/MxR09.png)');
    var outerdiv = $('.outerdiv');
    setTimeout(function() {
        outerdiv.addClass('outerdiv-opaque');
    }, 500);

}, 1000)

Answer №1

Revise the timeouts functions to improve efficiency. Adjust the .outerdiv-opaque styling

   .outerdiv-opaque {
      background-color: white;
    }

Once you separate your timeOut functions, they will appear as follows:

    var innerDiv = $('.innerdiv');
setTimeout(function() {
  innerDiv.css('background-image', 'url(https://i.sstatic.net/MxR09.png)');
}, 1000)

 var outerdiv = $('.outerdiv');
  setTimeout(function() {
    outerdiv.addClass('outerdiv-opaque');
  }, 500);

Answer №2

To maintain the original markup and ensure that the opacity doesn't affect any other elements, I recommend using a pseudo element like this.

Instead of relying on a script for the animation, consider adding an additional step in the animation sequence. This step instructs the element to keep its opacity at 1 until it reaches 60% of the total animation time, after which it should start to fade out.

.outerdiv {
  position: relative;
  height: 500px;
  width: 500px;
  color: white;
  background: url(https://i.sstatic.net/MxR09.png);
}
.outerdiv::before {
  content: '';
  background-color: black;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0.5;
  animation: fade 2s linear;
}
.innerdiv {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
p {
  position: relative;
}

@keyframes fade {
  0%   { opacity:1 }
  60%  { opacity:1 }
  100% { opacity:0.5 }
}
<div class="outerdiv">
  <div class="innerdiv">
  </div>
  <p>
    The text inside should remain solid white
  </p>
</div>

Answer №3

There are numerous ways to achieve this effect. Here, we present four simple examples that work seamlessly.

Utilizing CSS Transitions

HTML:

<div class="container">
  <div class="outerdiv">
  </div>
  <div class="innerdiv">
  </div>
  <p>
    content - should remain solid white
  </p>
</div>

CSS:

.container,.outerdiv {
  background-color: black;
  position: relative;
  display: block;
  height: 500px;
  width: 500px;
  color: white;
}

.outerdiv,.innerdiv {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.outerdiv{
  z-index:1;
  transition: .5s opacity linear;
}

.innerdiv{
  background-image: url(https://i.sstatic.net/MxR09.png);
}

.outerdiv.fadeout{
  opacity:0
}

.container p{
  position:relative;
  z-index:3;
}

JS:

// wait 1 second, add the fadeout class, let the CSS do the rest
setTimeout(function(){
  document.querySelector('.outerdiv').classList.add('fadeout')
},1000);

View it live: https://jsfiddle.net/kmm8e0x7/8/


Applying CSS Animation

HTML: same as above

CSS:

.container,.outerdiv {
  background-color: black;
  position: relative;
  display: block;
  height: 500px;
  width: 500px;
  color: white;
}

.outerdiv,.innerdiv {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.outerdiv{
  z-index:1;
}

.innerdiv{
  background-image: url(https://i.sstatic.net/MxR09.png);
}

.outerdiv{
  animation: fadeout .5s linear forwards 1s;      
  /* 
    Which is shorthand for:
      animation-name: fadeout 
      animation-duration: .5s;
      animation-timing-function: linear
      animation-fill-mode:forwards;
      animation-delay: 1s 
  */
}

.container p{
  position:relative;
  z-index:3;
}

@keyframes fadeout{
  from{opacity:1}
  to{opacity:0}
}

JS: none (animation-delay property eliminates the need for setTimeout)

See it in action: https://jsfiddle.net/kmm8e0x7/7/


Using JavaScript Approach

HTML: similar to above

CSS:

.container,.outerdiv {
  background-color: black;
  position: relative;
  display: block;
  height: 500px;
  width: 500px;
  color: white;
}

.outerdiv,.innerdiv {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.outerdiv{
  z-index:1;
  transition: .5s opacity linear;
}

.innerdiv{
  background-image: url(https://i.sstatic.net/MxR09.png);
}

.container p{
  position:relative;
  z-index:3;
}

JS:

var el = document.querySelector('.outerdiv');

function fadeout(){
  el.style.opacity -= 0.01;
  
  if(el.style.opacity !== 0){
      requestAnimationframe(fadeout);
      // this could just as easily be setTimeout(fadeout,t) where t = an increment of time after which to call the next frame
  }
}

// just use setTimeout to wait for 1 second before starting the fadeout
setTimeout(fadeout,1000);

See it in motion: https://jsfiddle.net/kmm8e0x7/6/


Implementing jQuery

HTML: same as above

CSS: same as above

JS:

$('.outerdiv').animate({
  'opacity': '0'
}, 500);

Witness it live: https://jsfiddle.net/kmm8e0x7/5/

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

Collaborative Artistry: Using HTML5, JavaScript, and Node.js for Multiplayer

Creating a multiplayer drawing application for touch-enabled devices has been a challenge. I have utilized Node.js with Socket.io to draw points on a canvas, but there's an issue with the touchend event not resetting properly. To illustrate, take a l ...

Can a variable be initialized with a concealed or additional argument?

After just 2 weeks of coding, I'm struggling to find information on how to initialize a variable with an extra argument in a recursive function call. Is this even possible? And if it is, are there any scenarios where it's considered best practice ...

Error: Authorization requires both data and salt arguments

As a novice in NodeJS, I attempted to create an authentication form using NodeJS + express. The issue I am facing is regarding password validation - specifically, when "confirmpassword" does not match "password", it should return nothing. Despite my effo ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

`Next application will have all accordions simultaneously opening`

Is there a way to make the accordion open only one item at a time? Currently, when I click on one accordion item, all of them expand simultaneously. The data is being fetched from a local JavaScript file and consists of a list of objects with questions a ...

Optimize data storage with javascript on Otree

I've been attempting to store the timestamp from a click in an Otree database, but I've tried using various codes without success. Here's the first code snippet: function myFunction() { var n = Date.now(); document.getElementById(" ...

Transforming JQuery code into pure Javascript: Attaching an event listener to dynamically generated elements

After exhausting all available resources on stack overflow, I am still unable to find a solution to my problem. I am currently trying to convert the JQuery function below into Vanilla JavaScript as part of my mission to make web pages free of JQuery. How ...

The total height of the document's body in jQuery is not equal to the sum of the viewport height and the window's scroll top position at the bottom of the document

Why does the document height appear smaller than the window scroll top value plus the viewport height when I reach the end of the document? Shouldn't they be equal? I've been struggling with this issue for hours and can't seem to figure it o ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...

Enhance the image by adding a magnifying glass effect when hovering over it in WordPress

I have a gallery located at this link. I would like to implement a magnifying glass effect when users hover over the images, making it clear that they can be enlarged. The desired effect is similar to the one shown here. I've searched through differe ...

Numerous clocks on display

I am trying to display two clocks on my webpage, but for some reason only one clock is showing up. The first clock script is as follows: <script type="text/javascript"> var tmonth=new Array("January","February","March","April","May","June","July"," ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

Using jQuery to trigger an action when a user clicks on a regular audio element

Is there a way to detect a click on the default audio element of a browser using jQuery? I'm having trouble getting it to work in Chrome. $('audio').click(function(){ alert("You have clicked on an audio player"); }); <script ...

Introducing Laravel 6's Hidden Gems: Unleash the Power of @push

Hey everyone, I'm a newcomer to the world of Laravel and currently using Laravel 6.0 I've encountered an issue with my javascript code that utilizes @push. Strangely enough, the script only functions properly when I manually insert the code into ...

Issue with module.exports entry in Webpack configuration causing errors

I've been working on setting up webpack but I've hit a roadblock due to this error message. It seems like there's an issue with the entry configuration. When I try to add it without specifying a path, as shown in the tutorial, I receive the ...

utilizing parent scope in a jQuery function callback

Currently, I am facing an issue concerning a jQuery callback working on a variable that is outside of its scope. To illustrate this problem, consider the code snippet below: $('#myBtn').on('click', function(e) { var num = 1; / ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Testing the updated version 18 of Create React APP index.js using Jest

Previously, I had this index.js file created for React version <= 17. import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import reportWebVitals from './reportWebVitals'; im ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...