[Javascript + CSS] Create Smooth UI Transitions with the Native View Transitions API

In this lesson, you'll learn how to implement smooth state transitions in your web applications using the browser's built-in View Transitions API. We'll create a simple example that demonstrates how to animate between different text states with just a few lines of code - no external libraries required. This powerful native API makes it easy to add professional-looking transitions to your user interface, enhancing the user experience with minimal effort.

 

import "./style.css";

const messages = [
	"Hello, world! 👋",
	"How are you? 😊",
	"View Transitions are cool! ✨",
	"Try clicking again! 🔄",
];

let currentIndex = 0;

const button = document.querySelector("#button") as HTMLButtonElement;
const content = document.querySelector("#content") as HTMLDivElement;

button.addEventListener("click", () => {
	if (!document.startViewTransition) {
		alert("Your browser doesn't support the View Transitions API");
		return;
	}

	const transition = document.startViewTransition(() => {
		currentIndex = (currentIndex + 1) % messages.length;
		content.textContent = messages[currentIndex];
	});
    
    transition.ready.then(() => {
        // Visiby disable the button
        button.style.pointerEvents = "none"
        button.style.opacity = "0"
    })
    
    transition.finished.then(() => {
        // Re-enable the button
        button.style.pointerEvents = "auto"
        button.style.opacity = "1"
    })
});

 

Customize View Transitions with CSS Using view-transition-old and view-transition-new

you'll discover how to style View Transitions using CSS pseudo-selectors to create custom animation effects. We'll transform the default cross-fade into a smooth slide transition by targeting the ::view-transition-old and ::view-transition-new pseudo-elements. You'll learn how these powerful selectors give you precise control over your transition animations, allowing you to create more engaging and personalized user experiences with just a few lines of CSS.

/*stylle.css*/

::view-transition-old(root) {
    animation: slid-out-to-right 0.3s ease-in-out both;   
}

::view-transition-new(root) {
    animation: slid-in-to-left 0.3s ease-in-out both;   
}

@keyframes slid-in-to-left {
    from {
        transform: translateX(-100%)
    }
    to {
        transform: translateX(0)
    }
}

@keyframes slid-out-to-right {
    from {
        transform: translateX(0)
    }
    to {
        transform: translateX(100%)
    }
}

 

posted @ 2024-12-09 15:49  Zhentiw  阅读(1)  评论(0编辑  收藏  举报