1

I'm looking for ideas to hide a div when it reaches another div and show it again when it passes the same div. There can also be multiple divs to pass. Something like:

 var bottom = $('.out-of-grid-images')

 $(window).scroll(function(){    
        if ($(this).scrollTop() > bottom){ 
            $('.share-icons').fadeOut(200); // hide share icons when reached and overlaps
        }
        else if ($(this).scrollTop() < bottom){ {
            $('.share-icons').fadeIn(200); // show icons when passed element
        }
    });

I can not produce a jsFiddle because I haven't found anything similar to work with. Any ideas?

EDIT:

The share icons are a fixed position element. The elements reached are dynamic and not fixed from top of the page (they are post content images out of the grid)

EDIT: here's an image to illustrate the matter enter image description here

user3615851
  • 999
  • 1
  • 15
  • 40

1 Answers1

0

What you'll want to do is have an Array of divs that you want to trigger the hiding effect, then calculate their bounding rectangle, and then perform collision detection on them.

Here is a very rough example - you'll have to fix the showing and hiding, as this will cause a fadeIn/fadeOut on each scroll event.

const shareIcons = $('.share-icons');
const divs = $('.trigger-div');
const rects = [];

divs.each(function () {
    rects.push(this.getBoundingClientRect());
});

$(window).scroll(function () {
    let interectsAny = false;
    rects.forEach(function (rect) {
        if (intersectRect(rect, shareIcons[0].getBoundingClientRect())) {
            interectsAny = true;
        }
    });
    if (interectsAny) {
        shareIcons.fadeOut(200);
    } else {
        shareIcons.fadeIn(200);
    }
});

// https://stackoverflow.com/questions/2752349/fast-rectangle-to-rectangle-intersection
function intersectRect(r1, r2) {
  return !(r2.left > r1.right || 
           r2.right < r1.left || 
           r2.top > r1.bottom ||
           r2.bottom < r1.top);
}
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66