Control CSS Animation with JavaScript Using KeyframeKit
@keyframes definitions into Web Animations API-compatible animation objects. It reads keyframe data directly from your document’s stylesheets or a fetched CSS file and returns a native Animation instance. That instance exposes the full Web Animations API — pause, reverse playback, playback rate control, progress tracking, and a finished promise.
@keyframes directly from document stylesheets.1. Install & import keyframekit.
# NPM $ npm install keyframekit
import KeyframeKit from 'keyframekit'; // OR Import the KeyframeKit module from unpkg import KeyframeKit from 'https://unpkg.com/keyframekit';
2. Play CSS-Defined Animations:
/* Declare a slide-in animation in your stylesheet */@keyframes slide-in-up {
from {
transform: translateY(40px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
} / Wait for document.readyState to reach 'complete', then return document.styleSheets
const docStyleSheets = await KeyframeKit.getDocumentStyleSheetsOnLoad();
// Search the stylesheets for the @keyframes rule named 'slide-in-up'
const slideInKeyframes = KeyframeKit.getStyleSheetKeyframes({
of: 'slide-in-up',
in: docStyleSheets
});
// Convert the parsed keyframes into a KeyframeEffectParameters instance
// Pass duration (ms) and a CSS easing function here
const slideInEffect = slideInKeyframes.toKeyframeEffect({
duration: 450,
easing: 'ease-out'
});
// Attach the effect to a DOM element and receive a native Animation instance
const heroAnim = slideInEffect.toAnimation({
target: document.querySelector('.hero-card')
});
// Start the animation
heroAnim.play(); // Pause the animation at its current frame
heroAnim.pause();
// Reverse direction — set to 2 for double speed, 0.5 for half speed
heroAnim.playbackRate = -1;
// Read the current position in the animation; value ranges from 0 (start) to 1 (end)
const progress = heroAnim.overallProgress;
console.log('Animation progress:', progress);
// Await the moment the animation finishes, then run follow-up logic
await heroAnim.finished;
console.log('Animation finished.'); 3. Import Keyframes from an External CSS File:
// Fetch the CSS file and parse it as a CSSStyleSheet object
// Note: @import rules inside this file are NOT resolved
const motionSheet = await KeyframeKit.importStyleSheet('./styles/motion.css');
// Extract the target @keyframes rule from the fetched stylesheet
const fadeOutKeyframes = KeyframeKit.getStyleSheetKeyframes({
of: 'fade-out-down',
in: motionSheet
});
// Build the effect and attach it to a DOM target
const panelEffect = fadeOutKeyframes.toKeyframeEffect({ duration: 280 });
const panelAnim = panelEffect.toAnimation({
target: document.querySelector('.side-panel')
});
panelAnim.play(); 4. Or define animations directly in JavaScript:
const textRevealAnim = new KeyframeEffectParameters({
keyframes: {
// offset runs from 0 to 1, equivalent to CSS percentage keyframe positions
offset: [0, 0.4, 1],
// clip-path values at each keyframe offset
clipPath: ['inset(0 100% 0 0)', 'inset(0 30% 0 0)', 'inset(0 0 0 0)'],
// opacity values at each keyframe offset
opacity: ['0', '0.5', '1']
},
options: {
duration: 550,
easing: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)'
}
});
// Attach to a DOM element; toAnimation() accepts a custom timeline via the 'timeline' key
const headingAnim = textRevealAnim.toAnimation({
target: document.querySelector('.section-heading'),
// Defaults to document.timeline; swap for ScrollTimeline or another AnimationTimeline
timeline: document.timeline
});
headingAnim.play(); 5. Extract all keyframes from a stylesheet at once:
const docStyleSheets = await KeyframeKit.getDocumentStyleSheetsOnLoad();
// Returns an object keyed by @keyframes rule name; each value is a ParsedKeyframes instance
const keyframesMap = KeyframeKit.getAllStyleSheetKeyframesRules({
in: docStyleSheets
});
// Access any animation by its CSS name
const bounceKeyframes = keyframesMap['bounce-in'];
if (bounceKeyframes) {
const bounceEffect = bounceKeyframes.toKeyframeEffect({ duration: 380 });
const badgeAnim = bounceEffect.toAnimation({
target: document.querySelector('.notification-badge')
});
badgeAnim.play();
} 6. The toKeyframeEffect method accepts standard Web Animations API timing properties.
duration (number): Sets the length of time the animation takes to complete one cycle (in milliseconds).easing (string): Sets the rate of change of the animation over time (e.g., ‘ease’, ‘linear’, ‘ease-in-out’).target (Element): Sets the DOM element to animate when calling toAnimation.timeline (AnimationTimeline): Sets the timeline associated with the animation. It defaults to document.timeline.7. API Methods.
// Fetches all stylesheets currently loaded in the document
await KeyframeKit.getDocumentStyleSheetsOnLoad();
// Fetches and parses a specific external CSS file
await KeyframeKit.importStyleSheet('./path/to/styles.css');
// Extracts a specific @keyframes rule from a stylesheet or list
KeyframeKit.getStyleSheetKeyframes({ of: 'animation-name', in: styleSheetObject });
// Extracts all @keyframes rules from a stylesheet or list
KeyframeKit.getAllStyleSheetKeyframesRules({ in: styleSheetObject });
// Converts parsed keyframes into a KeyframeEffect object
parsedKeyframes.toKeyframeEffect({ duration: 500 });
// Converts a KeyframeEffect into a playable Animation object
effect.toAnimation({ target: domElement });
// Starts or resumes the animation playback
activeAnimation.play();
// Pauses the animation playback
activeAnimation.pause();
// Reverses the animation playback direction
activeAnimation.playbackRate = -1; Q: Can I use KeyframeKit with a stylesheet loaded from a CDN or a different domain?
A: CORS restrictions block JavaScript from reading cssRules on cross-origin stylesheets unless the server sends an Access-Control-Allow-Origin header. The same restriction applies to importStyleSheet(), which uses fetch() internally. Host your animation CSS on the same origin, or configure your CDN to send the correct CORS headers on stylesheet responses.
Q: Does importStyleSheet() follow @import rules inside the fetched CSS file?
A: No. The library does not resolve @import rules. When the keyframes you need live in a file that another stylesheet imports, fetch and parse that file directly with a separate importStyleSheet() call.
Q: Can I run the same animation on multiple elements simultaneously?
A: Yes. Each call to toAnimation() produces an independent Animation instance for the element you pass to target. Call toAnimation() once per target element from the same KeyframeEffectParameters instance. Each animation plays, pauses, and tracks progress on its own.
Q: Is KeyframeKit compatible with scroll-driven animations?
A: The toAnimation() method accepts a timeline parameter that takes any AnimationTimeline-compatible object. Pass a ScrollTimeline (when browser support is present) to drive a CSS-defined animation with scroll position.
The post Control CSS Animation with JavaScript Using KeyframeKit appeared first on CSS Script.
Ryan Gosling has confirmed he's had discussions with Marvel to play flame-headed hero Ghost Rider.…
Project Hail Mary screenwriter Drew Goddard has said that the Sony hack of 2014 killed…
Cards on the table: I love Crimson Desert. And despite the mixed response it’s getting…
This review is based on a screening at the South by Southwest Film & TV…
The post Avid: Vast Majority Of Oscar-Winning Films Used Its Editing & Sound Tools appeared…
The post Inside The Mighty Production Engine Behind The NCAA Men’s Basketball Tournament’s First Week…
This website uses cookies.