0

I wanted to hide a sidebar element when it overlaps with the images on the page. I found a great answer on StackOverflow, but it doesn't entirely solve my problem. Right now, it only works with the first image on the page. It will hide the sidebar when it touches the first image. But it won't hide for the rest of the images. What should I do if I want it to work with all the images on the page?

Here is my code.

function collision ($div1, $div2) {
  var x1 = $div1.offset().left
  var y1 = $div1.offset().top
  var h1 = $div1.outerHeight(true)
  var w1 = $div1.outerWidth(true)
  var b1 = y1 + h1
  var r1 = x1 + w1
  var x2 = $div2.offset().left
  var y2 = $div2.offset().top
  var h2 = $div2.outerHeight(true)
  var w2 = $div2.outerWidth(true)
  var b2 = y2 + h2
  var r2 = x2 + w2

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) {
    $div1.addClass('show')
  } else {
    $div1.removeClass('show')
  }
}

window.setInterval(function () {
  collision($('#content-nav'), $('.image-container'))
}, 100)

Here is how it's working right now. https://i.stack.imgur.com/qG3MA.jpg

lucky13820
  • 71
  • 1
  • 8

1 Answers1

1

What's happening is that you're calling only the first element with the image-container class, so it'll only check the topmost image-container. You have to retrieve all instances of image-container and check against them for overlap.

Here's what your collision function would look like & a working JSFiddle

 function collision ($nav) {
  var x1 = $nav.offset().left
  var y1 = $nav.offset().top
  var h1 = $nav.outerHeight(true)
  var w1 = $nav.outerWidth(true)
  var b1 = y1 + h1
  var r1 = x1 + w1
  var hide = false 

$(".image-container").each(function() {

  var x2 = $(this).offset().left
  var y2 = $(this).offset().top
  var h2 = $(this).outerHeight(true)
  var w2 = $(this).outerWidth(true)
  var b2 = y2 + h2
  var r2 = x2 + w2

    if (!(b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2)) {
    hide = true;
  }
});
  if (!hide) {
    $nav.removeClass('hide')
  } else {
    $nav.addClass('hide')
  }
}
anmelikh
  • 26
  • 2