Is there a way to set IsInView to wait for each element with the same class, so I don’t have to call them one by one?
For example if I have three sections, I just want to call them like this:
$(".section").on('inview', function(event, isInView) {
if (isInView) {
$(this).show();
}
});
So that all three section appear one by one:
<div id="section-1" class="section">
</div>
<div id="section-2" class="section">
</div>
<div id="section-3" class="section">
</div>
EDIT:
I’ve also tried with each but that doesn’t work either:
$('.section').each(function() {
$(this).on('inview', function(event, isInView) {
if (isInView) {
$(this).show();
}
});
});
2
Answers
You could put them in promises and wait until they’re all finished with:
But I think your issue is not with async behaivour, but with the selector, cause I believe JQuery just gets one element when you do $(‘section’), so doing a forEach loop on that makes no sense. I am not sure how to do it with jquery, but I would do it like this
Nowadays jQuery is considered an overhead.
In pure, vanilla JavaScript the IntersectionObserver API is a good tool for the task:
For more observer options read: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options