Simple animations can be created with CSS by defining a start and end position and the duration taken to transition between these two states. The CSS then calculates all the intermediate positions for us.

To fade an element we can use the opacity and transition CSS properties.

Opacity specifies the transparency of an element (0 is transparent, 1 is opaque and a number in between eg, 0.6 will be semi-transparent). In this example we’ll start with the component at full opacity and then fade it out to be fully transparent.

First we need to identify the screen element to fade in and out in the HTML panel of the Developer Options. Once we’ve found it we can give it a class name so that we can reference it in the CSS and JavaScript. For example, a container component in Fliplet may look like this:

<fl-container cid=”86754”></fl-container>

We can choose any class name we wish. For this example we’ll choose a class called animate-fade and add it into the text component by adding the text class="animate-fade". See below:

<fl-container cid=”86754” class="animate-fade"></fl-container>

Then switching over to the CSS panel we can style our element by using the class name. The example below starts with the element shown to a user (ie, with opacity of 1. Opacity of 0 is transparent).

.animate-fade {
  opacity: 1;
}

We also want to specify a duration (aka a transition) for any animations applied to our element. Below, we’ve added a transition of 0.1 seconds.

.animate-fade {
  opacity: 1;
  transition: 0.1s;
}

Now that we’ve defined our starting parameters we want to define an end state.

To do this we will then create another style which is a combination of two class names. The first class name is the same as before (ie, ‘animate-fade’) but we’ve added another class name to it of ‘fade-out’. The opacity we want is now zero (ie, transparent). We don’t need to redefine the transition duration as this is already associated with anything with the class of ‘animate-fade’.

The end state of our CSS looks like this:

.animate-fade.fade-out {
  opacity: 0;
}

The final piece of the puzzle is to animate between the two states. We can do this dynamically with JavaScript by adding and removing the ‘fade-out’ class. Without it we’ll be in the first state (visible) but with it we’ll be in the second state (transparent).

The code below adds the ‘fade-out’ class to any element with the class ‘animate-fade’.

$(‘.animate-fade’).addClass(‘fade-out’);

To reverse the animation and fade-in the element, we can simply remove the ‘fade-out’ class.

$(‘.animate-fade’).removeClass(‘fade-out’);

If you don’t want to run the animation immediately, you can run the JavaScript based on a user interaction. For example, when a user taps a button. See this link for more details.

Was this article helpful?
YesNo