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

It's recommended to utilize the callback feature with setLoggedIn to ensure the previous state is captured effectively, as illustrated below:

To ensure capturing the previous state when using setLoggedIn, it is recommended to utilize the callback option. This will help in keeping track of changes and ensuring smoother functionality: ...

Having trouble with jquery's empty() function not functioning as expected

I'm brand new to using jquery so I apologize in advance for any beginner mistakes. Essentially, my issue is straightforward: Here is the HTML code I have: <div class="v" align="center" id="div4"> <div id="div5" class="h blurb"> <sp ...

How can I trigger a click event on a link using JQuery?

One of my links has the unique id: nyhedsklik There is a function associated with this link that activates when it is clicked: $('a.poplight[href^=#]').click(function() { var popID = $(this).attr('rel'); //Fetching Popup ...

Embeds and hyperlinks across various web pages

I created a webpage called A.html. Within this page, I have three other web pages named a1.html, a2.html, and a3.html. The goal is to always have a1, a2, and a3 open within an iframe inside A.html. Now, I have another webpage B.html which includes links t ...

Embrace the flexibility of using Next.js with or without Express.js

Recently, I started the process of migrating a project from create-react-app to next.js. However, I am facing uncertainty when it comes to migrating the backend of the project. Currently, my backend is built with an express server. In next.js, there are p ...

Text-color in the v-tooltip

Is there a way to change the text color of v-tooltips components without affecting the tooltip background color? I attempted to inspect the element, but the tooltip only appears on hover, making it impossible to inspect. Below is the code snippet: < ...

When utilizing jQuery and adding a script element dynamically, why does the file's URL get appended with "?_=timestamp"?

Imagine visiting a website with jQuery functionality, like . If we use the following code in the debug console: jQuery("body").append("<script src='http://code.jquery.com/jquery-1.9.1.js'></script>"); In both Chrome and Firefox, we ...

Preventing Other Devices from Establishing Connections

My goal is to restrict access to my website so that only mobile devices can enter. I have the ability to utilize node.js, HTML, and PHP in my website development. How can I go about blocking connections from other devices? ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

Avoid losing focus on href="#" (preventing the page from scrolling back up to the top)

Is there a way to prevent an empty href link from causing the page to scroll up when clicked? For example, if I have: <a href="#">Hello world</a> And this "Hello world" link is in the middle of the page. When clicked, the URL would look like ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Why @font-face doesn't display on older versions of Internet Explorer like IE 7 and IE

Our website has the following CSS code. The use of a smiley face is to ensure compatibility with IE 7 and IE 8. However, while the site's fonts display correctly on IE 9, Chrome, Firefox, etc., there seems to be an issue with IE 7 and 8. @font-face { ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Access PHP variables in JavaScript

In my project, I have a file named english.php which holds various variable values stored in the $LANG array. For example: $LANG['value_1']="abc"; $LANG['value_2']="xyz"; In addition to numerous .php files that include require_once( ...

Using jQuery, create a keypress event that functions like the tagging feature on Facebook when composing a wallpost and typing the "@" symbol

Hey everyone! I'm new to jquery and javascript, but I'm learning a lot. Currently, I'm working on replicating Facebook's user tagging feature in a wall post when the "@" symbol is input in a text area. I've already set up a functio ...

I've been attempting to align the iframe element in the center without success, despite trying out various solutions from

Despite trying to center-align the div using style="text-align: center;", display: block, and align="center", none of these methods seemed to work for me. Here is the code including all attempts: <div align="center" style="text- ...

Images in CSS not copied to the output directory when using Webpack

Using Webpack to bundle various javascript and css files on a website includes bundling bootstrap.css and chosen.css as part of the bundles. To achieve this, there is a main.js file serving as an entry point for importing all necessary files. The process i ...

What is the reason AJAX does not prevent page from refreshing?

Can anyone offer some guidance on using AJAX in Django? I'm attempting to create a basic form with two inputs and send the data to my Python backend without refreshing the page. Below is the AJAX code I am using: <script type="text/javascript& ...

Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: https://auth0.com/docs/quickstart/webapp/nextjs/interactive. However, I am now looking to upgrade my application to next ...