Reputation: 101
I've got three elements - every element is hidden from the start. If user scrolls onto them, they show up. I wrote a function that checks if element named bubbles is inside viewport. If it is, then function should show the rest of the elements.
But it doesn't. Element boxes is higher than element bubbles, and it also fires a function. But it shouldn't. I have no idea where the problem is.
document.addEventListener("scroll", checkViewport);
function checkViewport() {
var bubbles = document.getElementsByClassName("bubble-chat");
var boxes = document.getElementsByClassName("boxes");
var avatar = document.getElementsByClassName("msg-avatar");
for (let i = 0; i < avatar.length; i++) {
var bounding = bubbles[i].getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
) {
avatar[i].style.opacity = "1";
bubbles[i].style.opacity = "1";
(function(i) {
setTimeout(function() {
bubbles[i].style.display = "none";
boxes[i].style.opacity = "1";
}, 3000);
})(i);
}
}
}
Upvotes: 0
Views: 177
Reputation: 101
Well, I feel stupid. The code was okay all the time. I just commented one of the msg-text divs, and turns out, that it was the reason for the code to break.
Upvotes: 0
Reputation: 23360
you should also consider the scrolling positioning as the bounding box is relative to that. Fixed code:
bounding.top >= document.documentElement.scrollTop &&
bounding.left >= 0 &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <= document.documentElement.scrollTop + (window.innerHeight || document.documentElement.clientHeight)
Upvotes: 2