Home > Web Front-end > CSS Tutorial > How Can I Trigger CSS Animations with JavaScript on Scroll?

How Can I Trigger CSS Animations with JavaScript on Scroll?

Linda Hamilton
Release: 2024-12-06 19:28:12
Original
633 people have browsed it

How Can I Trigger CSS Animations with JavaScript on Scroll?

Trigger CSS Animations in JavaScript

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);
}
Copy after login

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');
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template