JavaScript TransitionEvent elapsedTime
Property: Understanding Transition Durations
The elapsedTime
property of the JavaScript TransitionEvent
interface is a crucial element for working with CSS transitions. It provides the duration, in seconds, that the transition has been running when the event was triggered. This property is particularly useful for synchronizing JavaScript animations with CSS transitions, creating smoother and more visually appealing user interfaces. This article will thoroughly explain the elapsedTime
property, including its syntax, usage, and real-world examples.
What is the TransitionEvent
elapsedTime
Property?
The elapsedTime
property, found within the TransitionEvent
object, is a read-only attribute that returns a floating-point number representing the amount of time the CSS transition has been running when a transitionend
event occurs. This value is always in seconds. Knowing the precise elapsed time can allow JavaScript to fine-tune animations and interactive elements that depend on CSS transitions.
Purpose of the elapsedTime
Property
The primary purpose of the elapsedTime
property is to:
- Synchronize Animations: Align JavaScript animations or effects with the completion of CSS transitions.
- Monitor Transition Progress: Track how far a CSS transition has progressed in time.
- Enable Dynamic Behavior: Trigger specific actions based on the transition’s elapsed time.
- Create Complex Interactions: Develop more intricate UI components that rely on precise transition timing.
Syntax of TransitionEvent
elapsedTime
The syntax for accessing the elapsedTime
property is straightforward. It can only be accessed within the scope of a transitionend
event listener, as it becomes available once a CSS transition has completed or interrupted.
element.addEventListener('transitionend', (event) => {
const timeElapsed = event.elapsedTime;
// Use the timeElapsed value here
});
Key Characteristics of elapsedTime
Characteristic | Description |
---|---|
**Data Type** | Floating-point number (seconds). |
**Read-Only** | The value of `elapsedTime` cannot be set or modified. |
**Accuracy** | The value represents the time the transition has run at the time the transitionend event was triggered. |
**Event Context** | Accessible only within a `transitionend` event listener. |
Examples of Using elapsedTime
Let’s explore several practical examples demonstrating how to effectively use the elapsedTime
property.
Basic Example: Logging the Elapsed Time
This basic example shows how to get the elapsedTime
when a CSS transition ends and log it to the console.
<div id="box1" style="width: 100px; height: 100px; background-color: lightblue; transition: width 1s;"></div>
<script>
const box1 = document.getElementById('box1');
box1.addEventListener('click', function() {
box1.style.width = '200px';
});
box1.addEventListener('transitionend', function(event) {
console.log('Transition ended. Elapsed time:', event.elapsedTime, 'seconds');
});
</script>
Output
- When the div is clicked, its width transitions from 100px to 200px.
- Once the transition finishes, the elapsed time is logged to the console like:
Transition ended. Elapsed time: 1.002 seconds
In this example, clicking the box triggers a width transition. The transitionend
event listener logs the exact time the transition ran. The value will be approximately 1 second, as we set the transition duration to be 1 second in CSS.
Using elapsedTime
for Synchronization
In this example, we’ll use elapsedTime
to start a JavaScript animation precisely when a CSS transition finishes.
<div id="box2" style="width: 100px; height: 100px; background-color: lightgreen; transition: transform 0.5s;"></div>
<div id="box2_anim" style="width: 30px; height: 30px; background-color: orangered; position: absolute; top: 110px; left: 10px; display: none"></div>
<script>
const box2 = document.getElementById('box2');
const box2_anim = document.getElementById('box2_anim');
let animation_start_time;
box2.addEventListener('click', function() {
box2.style.transform = 'rotate(90deg)';
});
box2.addEventListener('transitionend', function(event) {
box2_anim.style.display = "block";
animation_start_time = performance.now();
requestAnimationFrame(animate_box_2);
});
function animate_box_2(timestamp) {
if (!animation_start_time) {
animation_start_time = timestamp;
}
const progress = (timestamp - animation_start_time) / 1000;
box2_anim.style.left = 10 + progress * 100 + "px";
if (progress < 2) {
requestAnimationFrame(animate_box_2);
} else {
box2_anim.style.display = "none";
animation_start_time = undefined;
}
}
</script>
Output:
- When the green box is clicked, it rotates 90 degrees.
- Simultaneously, a small red box appears at the bottom and moves horizontally for 2 seconds after the green box has finished rotation.
In this code, the transitionend
event triggers a JavaScript animation by calling the animate_box_2()
function after the rotation has ended. The red box animates to the right and disappears after 2 seconds, demonstrating how the elapsedTime
property can be used to start JavaScript animations when a CSS transition finishes.
Complex Transition Synchronization
Let’s create a slightly more complex example where we use elapsedTime
in conjunction with other transition properties.
<div id="box3" style="width: 100px; height: 100px; background-color: lightcoral; transition: all 0.8s ease-in-out;"></div>
<p id="elapsedTimeDisplay3" style="font-size:12px;">Elapsed Time: 0 seconds</p>
<script>
const box3 = document.getElementById('box3');
const elapsedTimeDisplay3 = document.getElementById('elapsedTimeDisplay3');
box3.addEventListener('click', function() {
box3.style.width = '150px';
box3.style.height = '150px';
box3.style.borderRadius = '50%';
});
box3.addEventListener('transitionend', function(event) {
elapsedTimeDisplay3.innerText = `Transition ended for property ${event.propertyName} in ${event.elapsedTime.toFixed(2)} seconds`;
});
</script>
Output:
- When the div is clicked, it transforms into a circle, both its width and height change and it also gets rounded corners with a 0.8 seconds transition.
- Once the transition finishes, it logs which CSS property transition ended with its elapsed time. For example,
Transition ended for property border-radius in 0.80 seconds
This example demonstrates how the elapsedTime
property can be used with other properties of the TransitionEvent
object, such as propertyName
. The transition is applied to multiple properties, and we log each one separately. This approach provides more control over transition behavior.
Real-World Applications
The elapsedTime
property has many uses in creating engaging web experiences:
- Dynamic Loading Indicators: Display a loading animation that syncs with a transition.
- Interactive UIs: Trigger additional animations or effects after a UI element finishes its transition.
- Custom Tooltips: Animate the appearance of tooltips using CSS transitions and position them when the transition ends.
- Page Transitions: Create smooth page transitions that coordinate with JavaScript animations.
- Progress Bars: Show progress in loading by syncing with animations that are based on transition times.
Browser Support
The TransitionEvent
interface and its elapsedTime
property have excellent browser support across all modern browsers.
Note: While support is comprehensive, it is always good practice to test your code in multiple browsers. 🧐
Conclusion
The elapsedTime
property of the TransitionEvent
interface is a vital tool for web developers looking to create complex and synchronized animations. By leveraging this property, you can ensure your JavaScript animations and effects align seamlessly with CSS transitions, leading to a more polished and engaging user experience. From simple logging of transition times to the synchronization of complex animations, the elapsedTime
property provides precision control over transition-based interactions.