Recently, I was working on a similar concept for a web scraping project.
Here is a snippet of code that could be useful:
function checkIfIconInViewport() {
// defining current viewport (using both methods for maximum browser compatibility)
const viewportHeight =
window.innerHeight || document.documentElement.clientHeight;
// Retrieving the Icon
let icon = document.getElementById('icon');
let iPos = icon.getBoundingClientRect();
// Showing the icon if any part is visible:
if (viewportHeight - iPos.top > 0 && iPos.bottom > 0) {
icon.style.visibility = visible;
}
else { icon.style.visibility = hidden; }
// Showing the icon only if fully visible:
if (iPos.bottom > 0 && iPos.top >= 0) {
{
icon.style.visibility = visible;
}
else { icon.style.visibility = hidden; }
// Add && iPos.bottom <= viewportHeight for large elements.
{
// Running the function each time the window is scrolled.
document.addEventListener('scroll', checkIfIconInViewport);
Essentially, we are checking the position of the element (in this case, an icon) within the viewport every time a scroll event occurs.
Negative values or values exceeding the viewport height indicate that the element is outside the viewport boundaries.
I hope this provides some insight! If you are dealing with multiple objects, consider grouping them into an array to optimize the checking process and avoid redundant function definitions.
Edit: Upon reflection, I realize I may have misinterpreted your question. You might only need the latter part of the code, where the icon's visibility is set to hidden on scroll events. Is this the behavior you are aiming for?