0

I mix different sources (thank's to them) to achieve what we need. We have a div following the mouse ... it's ok ... but we need to toggle/add a class when this div overlapsing an other fixed div in the dom.

function detection(){
           
          const animalEl = document.getElementById("animal");
          const targetEl = document.getElementById("target");
  
          
          const a = animalEl.getBoundingClientRect();
          const b = targetEl.getBoundingClientRect();
      
            var overlap = (
              a.right == b.left ||  // right to left touching
              a.left == b.right ||                 // left to right touching
              a.bottom == b.top ||                 // bottom to top touching
              a.top == b.bottom)                   // top to bottom touching

            if(overlap){
              console.log("overlaps");
              targetEl.classList.toggle("touched");
            }else{
              //console.log("non");
            }
          
         
}

Here is a pen

https://codepen.io/vinchoz/pen/QWdmVza

I tried with "getBoundingClientRect()" but not sure to use it the right way...

Could a javascript guru have a look at it? Thank's

Vinch
  • 13
  • 5

1 Answers1

0

YES... I did find a solution

function detection(){
       
      const animalEl = document.getElementById("bee");
      const targetEl = document.getElementById("target");

      
      const a = animalEl.getBoundingClientRect();
      const b = targetEl.getBoundingClientRect();
      
            
      /*  FOR COVER
        var inside = (
          ((b.top <= a.top) && (a.top <= b.bottom)) &&
          ((b.top <= a.bottom) && (a.bottom <= b.bottom)) &&
          ((b.left <= a.left) && (a.left <= b.right)) &&
          ((b.left <= a.right) && (a.right <= b.right))
        )      
          
         if(inside){
          targetEl.classList.toggle("inside");
          }else{
            
          }
       */


      /* FOR TOUCHING */

        var touched = !(
          b.top > b.bottom ||
          a.right < b.left ||
          a.bottom < b.top ||
          a.left > b.right
        )    
        
        if(touched){
          targetEl.classList.add("touched");
        }else{
          targetEl.classList.remove("touched");
        }
      
     
    }

https://codepen.io/vinchoz/pen/QWdmVza

Vinch
  • 13
  • 5