Reputation: 417
I'm working on a project in Vue and need that when the user scrolls the page and arrive at a specified div, an effect or a class is added in that div, similar to ScrollReveal
Has anyone ever had to do something similar in Vue?
Here's the css code I own and I need it to run upon arriving in div
The title effect on h2 must be executed when it is displayed on the screen.
@keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
h1 {
animation: 1s ease-out 0s 1 slideInFromLeft;
}
h2 {
animation: 1s ease-out 0s 1 slideInFromLeft;
}
<h1>
Hello World!
</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h2>
World Hello!
</h2>
Upvotes: 2
Views: 637
Reputation: 3244
We can achieve the scroll to reveal effect by adding the the class slide
having your css animation property set, when the user scrolls to its position. Below is a working example:
new Vue({
data: {
el: document.getElementById('target-element')
},
methods: {
isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
},
handleScroll() {
/* if scrolled into view */
if(this.isScrolledIntoView(this.el))
this.el.classList.add('slide');
}
},
created() {
window.addEventListener('scroll', this.handleScroll);
},
});
@keyframes slideInFromLeft {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
.slide {
animation: slideInFromLeft 1s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<h1 class="slide">
Hello World!
</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h2 id="target-element">
World Hello!
</h2>
Upvotes: 1