FCD
FCD

Reputation: 135

Trigger CSS animation when it comes into viewport

I'm trying to make a border around a bootstrap 4 circular image. I want it to animate like the border in the codepen example below, but I want it to load when the user scrolls down. As I understand it I need to use Javascript to trigger it, but I'm not sure on how I can do that. Can someone help me?

https://codepen.io/katmai7/pen/jCAhv

<div class="wrap">
<div class="circle">
   <i class="icon i1 icon-terminal"></i>
   <i class="icon i2 icon-code-fork"></i>
   <i class="icon i3 icon-keyboard"></i>
   <i class="icon i4 icon-code"></i>
   <div class="line1"></div>
   <div class="line2"></div>
   <span class="text">hover on me</span>
 </div>
</div>

Upvotes: 1

Views: 1272

Answers (3)

DRC
DRC

Reputation: 5048

You can use the new Intersection observer api https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API where a polyfill is available here: https://github.com/w3c/IntersectionObserver/tree/master/polyfill

the code would be something like this:

let options = {
root: document.querySelector('.wrap'),
rootMargin: '0px',
threshold: 1.0
}
let element = document.querySelector('.circle')
let observer = new IntersectionObserver(() => element.classList.add('onviewport') , options);

also you should modify your css to not listen on hover triggers but "respond" to a class : modifying

&:hover{

to

&.onviewport {

If you don't want to use the Intersection observer api you can use a plugin like this one https://github.com/imakewebthings/waypoints , the logic would still be similar.

Upvotes: 2

Ignacio Ara
Ignacio Ara

Reputation: 2582

You can detect the scroll using

window.onscroll = function(e) {
    // Scroll up or down
}

The animation appears when

&:hover{
    animation: border .4s ease 1 forwards;
    cursor: none;
    [...]

So you'll need to add all that CSS to a new id and when you detect scroll add it to your element using JavaScript:

.newClass{
    animation: border .4s ease 1 forwards;
    cursor: none;
    [...]

Add it:

var element = document.getElementById("element-id");
element.className += " newClass";

Upvotes: 1

Ashley Marsh
Ashley Marsh

Reputation: 1

The animation-fill-mode property specifies a style for the element when the animation is not playing (before it starts, after it ends, or both). CSS animations do not affect the element before the first keyframe is played or after the last keyframe is played.

Upvotes: 0

Related Questions