Face to not see advantage in transforming your JS in jQuery, until pq with JS you can easily use the Intersection Observer
to "observe" the element that wants to place the class and only do this when it enters the screen, or as you say, when it is in focus. See the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
I won’t dwell on the details of the API, but the config I made was for when the element has 50% of it inside the screen it adds the class, you can control it here const options = { threshold: 0.5 };
values range from 0 to 1, so 0.5 is 50%. If you do not want to use the element size and use a fixed measure, you can remove the threshold
and use the rootMargin
. If you want the element between 25px on the screen before applying the class vc can put for example rootMargin: "-25px 0px",
in place of threshold
.
Another thing is you don’t need to do the classList
like you did, you can put everything together by separating by comma...
.classList.add("animated", "fadeInUp", "delay-2s", 'ativo');
The effect would be like this.
Follows the code.
const sec = document.querySelector('div');
const options = {
threshold: 0.5
};
const obs = new IntersectionObserver(function(entradas, obs) {
entradas.forEach(entra => {
if (!entra.isIntersecting) {
return;
}
entra.target.classList.add("animated", "fadeInUp", "delay-2s", 'ativo');
obs.unobserve(entra.target);
});
}, options);
obs.observe(sec);
body {
margin-top: 120vh;
}
div {
height: 100px;
width: 100px;
border: 1px solid #000;
}
.ativo {
border: 2px solid red;
}
<div></div>
Dude, but in your script you haven’t written the word Focus at all... What do you mean where I’m going wrong, it’s kind of obvious, right?! If you don’t have Focus in the code how do you want it to work? Your question doesn’t even make sense
– Caetano Sincero
I don’t think you understand the spirit of it. when I wrote Focus, I was not referring to the moment when the scroll arrives at the position where the element is in order for the DELE effect to happen. Got it? It is worth noting that with the JS code works as expected!
– Carlos Rocha