In the absence of jQuery, triggering CSS animations through JavaScript is a viable option. This guide provides a concise method to achieve this when the user scrolls the page.
Triggering CSS Animation with Class Manipulation
The simplest approach to triggering CSS animations is by modifying the presence of a class, allowing the styles defined within to take effect. To accomplish this with pure JavaScript:
function addClass(element, className) { element.classList.add(className); } function removeClass(element, className) { element.classList.remove(className); }
In your provided example, you have CSS classes for animations already defined: "anim" and "anim2." You can start the animation by adding these classes to the respective elements:
function start() { addClass(document.getElementById('logo'), 'anim'); addClass(document.getElementById('earthlogo'), 'anim2'); }
Triggering Animation on Page Scroll
Lastly, to initiate the animation when the page is scrolled, you can utilize the "window.addEventListener" function:
window.addEventListener('scroll', start);
This will invoke your "start" function whenever the page is scrolled, triggering the CSS animations.
Additional Note
Animations defined in CSS using keyframes can be similarly triggered by adding or removing classes. However, it's essential to ensure that the element in question has a defined transition property to enable the animation to take effect.
The above is the detailed content of How Can I Trigger CSS Animations with JavaScript on Scroll?. For more information, please follow other related articles on the PHP Chinese website!