Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS transition opacity only from 0 to 1, or alternative transition effect

I have a div element in which all my HTML are inserted. I want to create a fade in effect when the content of this div changes. Currently I set the opacity to 0 before inserting something to this div and then set it to 1, so that the effect takes place. The problem with my CSS is that is works for both cases, either for going from 0 to 1 or 1 to 0. Is there a way to make it work only when transitioning from 0 to 1; Is there a better alternative for transitioning from one page to another in a single page app?

HTML

<!DOCTYPE html>
<html>
<!-- Imports -->
    <body>
        <div id="app" class="app"></div>
     </body>
</html>

CSS

.app
{
    background-color:#f8f8f8;
    opacity:0;
    transition: all 1s;
   -webkit-transition: all 1s;
}

Javascript

When the page loads the opacity is set to 1 and the effect takes place:

document.getElementById("app").style.opacity='1';

The problem occurs when another page is loaded, where the opacity is now set to 0, thus making the transition take effect again.

Edit Updated with better explanation of the problem:

The opacity of the element does not change. What I want for the opacity is only to work when going from 0 -> 1, so that before I insert new content is set to 0 again (thus making the effect taking place, this is the problem) and when all the data have been inserted, a fade in (opacity going from 0 to 1) effect will take place.

like image 981
user1798707 Avatar asked Feb 11 '19 20:02

user1798707


2 Answers

I would add a class which is responsible for the transition. If you only add the transition rule only within the class, you'll get the one-way transition you're after:

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('.app').classList.toggle('change');
});
.app {
  background-color:#f8f8f8;
  opacity:0;
}

.app.change {
  opacity: 1;
  transition: all 1s;
}
<div class="app">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad nesciunt adipisci, ab ea deleniti ullam eius alias aperiam, explicabo dolore nihil, ex dolores perferendis. Commodi ipsa dignissimos magni consectetur soluta!</div>

<button>toggle opacity</button>
like image 184
Andy Hoffman Avatar answered Sep 23 '22 02:09

Andy Hoffman


You can add the transition property only when you want it to animate. I'll show you how to do it with two classes.

.app {
 background-color:#f8f8f8;
 opacity: 0;
}
.app.is-loaded {
 transition: all 1s;
 -webkit-transition: all 1s;
 opacity: 1;
}

...

document.getElementById("app").classList.add('is-loaded');

Now when you remove that class, the opacity won't have a transition back to 0.

like image 34
sallf Avatar answered Sep 23 '22 02:09

sallf