JQuery's animation techniques are known for their "pessimistic" approach, as they rely on timers to adjust opacity in the DOM step by step, leading to frequent redraws by the browser. This method was initially used before CSS transitions were widely available, making it the go-to technique for achieving such effects.
However, a more efficient approach now exists by utilizing CSS transitions, enabling the browser to handle most of the work seamlessly. Instead of JQuery directly manipulating opacity, you can simply apply a class and let the browser manage the transition between states.
Many modern browsers optimize opacity and transform transitions using GPU acceleration.
setTimeout(function() {
$('.fader').addClass('show');
$('.fader').on('click', function() {
$(this).removeClass('show');
});
});
.fader {
width: 200px;
height: 200px;
background: cornflowerblue;
opacity: 0;
transition: opacity 2s linear;
}
.show {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fader">I'll fade in, click me to fade out</div>
In the provided example, setTimeout()
is utilized to allow the DOM to render a frame with a <div>
containing the fader
class and an initial opacity
of 0
. Subsequently, the show
class is applied in the next frame, setting the opacity
to 1
. With a duration of 2 seconds set for the transition
, a gradual fade-in effect is achieved.
An additional feature includes a click event that removes the show
class, resulting in a smooth fade-out animation.