Altering the display attribute cancels out any opacity transitions

When using JavaScript to change the opacity of an element with transition: opacity 1s, the expected duration of one second is met, as demonstrated here:

onload = e => {
  var p = document.getElementsByTagName("p")[0];

  p.style.opacity = 1;
};
p {
  opacity: 0;
  transition: opacity 1s;
}
<p>
Lorem ipsum...
</p>

However, if the element has display: none and is first changed to display: initial (to make it visible) before adjusting the opacity, the transition ceases to work. This can be seen here:

onload = e => {
  var p = document.getElementsByTagName("p")[0];

  p.style.display = "initial";
  p.style.opacity = 1;
};
p {
  display: none;
  opacity: 0;
  transition: opacity 1s;
}
<p>
Lorem ipsum...
</p>

What is causing this behavior?

Note: There is no intention to use a transition on the display attribute or search for workarounds related to it.

Answer №1

Summary: It is not possible to use the transition property with the display property directly. Furthermore, applying the transition property to any CSS property of an element with a current display property of none will not work as intended.


To address this limitation, a solution would be to transition both the width and opacity properties simultaneously.

You can view an example demonstrating how the width and height properties can replicate the behavior of the display:none property in this JSFiddle.

The usage of the <span> element illustrates that the hidden <p> tag does not contribute to document flow.

The provided Snippet showcases code attempting to achieve the desired effect, although the transition may not function due to certain reasons.

var p = document.getElementsByTagName("p")[0];

p.style.width = "50%";
p.style.height = "auto";
p.style.opacity = 1;
html, body{width: 100%; height: 100%; margin: 0; padding: 0;}
p {
  width: 0;
  height:0;
  opacity: 0;
  transition: width 2s, opacity 3.5s;
  float:left;
  margin: 0;
}
<p>
Lorem ipsum...
</p>
<span>Right side text</span>

If absolutely necessary to utilize display:none, the mentioned css article proposes using a setTimeout() workaround to apply the transition property after toggling the display property, rather than during the toggle:

var p = document.getElementsByTagName("p")[0];
p.style.display = "block";

setTimeout(function(){p.style.opacity = 1;},1000);
p {
  display: none;
  opacity: 0;
  transition: opacity 1s;
}
<p>
Lorem ipsum..
</p>

Answer №2

Upon further analysis, it appears that the issue arises from the transition attempting to occur while the display attribute is in the process of changing. This results in the element still being hidden (display: none) and thus the transition failing to take effect. In theory, the transition could have initiated while the element was still set to display: none and only become visible once the switch to display: initial was complete. However, this scenario does not seem to be the case.

Demonstrated by the ability to adjust the opacity of an element with display: none prior to setting it to display: initial, as shown below:

var p = document.getElementsByTagName("p")[0];
p.style.opacity = 0.3;
p.style.display = "initial";
p {
  display: none;
  opacity: 0;
  transition: opacity 1s;
}
<p>
Lorem ipsum...
</p>

Furthermore, adjusting the opacity afterwards is also achievable, which leaves our initial hypothesis as the likely cause.

To ensure that the initial process completes before triggering the transition, incorporating a slight delay like the example below proves to be successful:

var p = document.getElementsByTagName("p")[0];

p.style.display = "initial";
setTimeout(function() {
p.style.opacity = 1;
},100);
p {
  display: none;
  opacity: 0;
  transition: opacity 1s;
}
<p>
Lorem ipsum...
</p>

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

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Is there a potential race condition in React when switching between lists?

I'm currently working on setting up a queue system where users can move items between different lists, such as from "available" to "with client". The queue's state is managed in the root React component like this: this.state = { queue: { a ...

What is the best way to incorporate Drift bot JS code into a static React NextJs application, such as a landing page?

I'm a beginner with ReactJS and I recently created a static website using ReactJS & NextJs. I decided to integrate a chatbot called 'Drift', but when following the installation instructions to insert JavaScript code in the <head> of HT ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

How can you retrieve the keys of an object that conforms to an interface?

In the following demonstration, we have two objects - KEYS and KEYS2. When importing KEYS in index.ts, autocomplete suggestions are available for K1 and K2 because KEYS does not adhere to an interface. On the other hand, with KEYS2, autocomplete is not pr ...

What is the best way to locate the position of a different element within ReactJS?

Within my parent element, I have two child elements. The second child has the capability to be dragged into the first child. Upon successful drag and drop into the first child, a callback function will be triggered. What is the best way for me to determi ...

Unable to modify div style using a JS function

I am attempting to show different divs based on the button clicked, with all starting with a display style of "none" except for one default div called "atualizacoes". After clicking a button, all divs should be set to display="none", and then the specific ...

React Native animation encountered a rendering issue: Invalid transform scaleDisliked value: { "scaleDisliked": 1 }

While working on my react native app, I encountered an issue when trying to apply a transform:scale effect to an Animated.View component. I am using interpolate for this purpose, but unfortunately, I keep receiving the following error message: Render error ...

What is the best way to vertically center my footer text?

footer { text-align: center; color: #FFF; position: fixed; bottom: 0px; width: 100%; height: 90px; background-color: #464646; } <footer> &copy; Name </footer> I am looking to center my name within the footer, however, it cu ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

How can I display a button (hyperlink) on a new line using CSS or jQuery?

I am looking to create a new line after the last input of my form. On this new line, I want to add a "remove-link". This is my HTML: <div class="subform dynamic-form"> <label for="id_delivery_set-0-price"> Price: </label> <inp ...

The MUI Slider Component is causing the entire page to go blank

I have implemented the Range Slider component: import React from 'react'; import Box from '@mui/material/Box'; import Slider from '@mui/material/Slider'; function valuetext(value) { return `${value}°C`; } export default f ...

Error Alert: React Native object cannot be used as a React child within JSON, leading to an Invariant Violation

When using React-Native: To start, here is the example code of a json file: Any placeholders marked with "..." are for string values that are not relevant to the question. [ { "id": "question1" "label": "..." "option": [ { "order": 1, "name": "..."}, ...

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

Having trouble with Jquery's .mouseover() method? Let's catch the solution!

I'm currently working on a jQuery homework assignment and I've been attempting to enhance the mouseover feature, but unfortunately, it's not functioning as expected. $("button").mouseover(function() { $(this).css({ left: (Math.rando ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

The variable referencing an unidentified function has not been defined

I've created an anonymous function assigned to a variable in order to reduce the use of global variables. This function contains nested functions for preloading and resizing images, as well as navigation (next and previous). However, when I try to run ...

Encountering an NPM start issue

I encountered an error while trying to execute the "npm start" command on my Windows 10 machine. My npm version is 2.13.3 and I am attempting to run an Express server. 0 info it worked if it ends with ok 1 verbose cli [ 'node', 1 verbose cli & ...

Error Encountered: Angular JS Throwing Unhandled Injection Error

I am having trouble validating the fields in my index.html and js files. I keep seeing errors, even after trying different versions of angular-route.min.js and angular.js. AngularJs | Basic Login Form <body ng-app="myApp"> ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...