Reputation: 43
I am still learning web designing and I wanted to start an animation on a div which is in middle of the page. I searched for it but everywhere I found it using j-query. Is there any way it can be done using pure CSS and JavaScript.
<div>A lot of contents which take whole screen</div>
<div>Section where animation has to happen when come into view</div>
Please help if it can be done using javascript only and if not then what is the easiest way of doing it.
Upvotes: 4
Views: 1729
Reputation: 2445
IntersectionObserver
Thus "No need to enter JS on every scroll." - A Haworth's comment
.repeat(500)
in js)var elements;
var windowHeight;
document.getElementById('content').innerText = "A lot of content to fill up the page. ".repeat(500)
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const square = entry.target.querySelector('.noanimfornow');
if (entry.isIntersecting) {
square.classList.add('animateme');
return; // if we added the class, exit the function
}
// We're not intersecting, so remove the class!
square.classList.remove('animateme');
});
});
observer.observe(document.querySelector('.animwrapper'));
@keyframes myanim {
from {
opacity: 0;
transform: scale(.7, .7)
}
to {
opacity: 1;
}
}
.animateme {
animation: myanim 5s;
}
.noanimfornow {
opacity: 0;
}
<div id="content"></div>
<div class="animwrapper">
<div class="noanimfornow">Section where animation has to happen when come into view</div>
</div>
Upvotes: 2
Reputation: 2445
js
answervar elements;
var windowHeight;
document.getElementById('content').innerText = "A lot of content to fill up the page. ".repeat(500)
function init() {
elements = document.querySelectorAll('.noanimfornow');
windowHeight = window.innerHeight;
}
function checkPosition() {
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var positionFromTop = elements[i].getBoundingClientRect().top;
//console.log(positionFromTop,windowHeight);
if (positionFromTop - windowHeight <= 0) {
element.classList.add('animateme');
element.classList.remove('noanimfornow');
}
if (positionFromTop - windowHeight > 0) {/*newly added:Edit2*/
element.classList.add('noanimfornow');
element.classList.remove('animateme');
}
}
}
window.addEventListener('scroll', checkPosition);
window.addEventListener('resize', init);
init();
checkPosition();
@keyframes myanim {
from {
opacity: 0;
transform: scale(.7, .7)
}
to {
opacity: 1;
}
}
.animateme {
animation: myanim 5s;
}
.noanimfornow {
opacity: 0;
}
<div id="content"></div>
<div class="noanimfornow">Section where animation has to happen when come into view</div>
noanimfornow
,js
we check the position of scroll, and set the class to animateme
when it reaches into view,init
function if needed in js
css
Upvotes: 4