skip to Main Content

In this example obviously my div intersects the bottom of the page, how can I know from javascript if this element is intersecting it or not?

if for example: bottom:0px; not should be intersected

.fixed{
  position:fixed;
  bottom:-10px;
  left:0px;
  width:300px;
  height:300px;
  background:blue;
  border:3px solid red;
}
<div class="fixed"></div>

2

Answers


  1. I took reference from this tutorial, where the code checks to see if the element is in the viewport.

    The code works by checking the element’s position using getBoundingClientRect() against the viewport’s height using documentElement.clientHeight.

    In your case, since you only want to check if the bottom border overlaps, I modified the code such that only domRect.bottom is checked.

    Finally, this method will show bottom:0px; as intersecting, and bottom: 1px; as non-intersecting. If you want bottom:0px; to intersect, add 1 to documentElement.clientHeight

    function isInterectingBottom(ele) {
        const domRect = ele.getBoundingClientRect();
        console.log(domRect.bottom);
        console.log(document.documentElement.clientHeight);
        return (
          domRect.bottom >= document.documentElement.clientHeight + 1
        );
      }
      
      const ele = document.querySelector('.fixed');
      console.log(isInterectingBottom(ele));
    .fixed{
      position:fixed;
      bottom:-10px;
      left:0px;
      width:300px;
      height:300px;
      background:blue;
      border:3px solid red;
    }
    <div class="fixed"></div>
    Login or Signup to reply.
  2. You can use getBoundingClientRect() function. It provides information about the size of an element and its position relative to the viewport.

    Then by comapring it to window.innerHeight you can tell if it intersects the screen or not.

    var elmBottom = document.querySelector(".fixed").getBoundingClientRect().bottom;
    
    if(elmBottom > window.innerHeight) console.log("elm intersects the bottom");
    else console.log("elm still fully in view");
    .fixed{
      position:fixed;
      bottom:-10px;
      left:0px;
      width:300px;
      height:300px;
      background:blue;
      border:3px solid red;
    }
    <div class="fixed"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search