Mouse Hover Selection

by Ben Clayton

HTML

<div id="block1" class="block">1
  <div id="block2" class="block">2
    <div id="block5" class="block abs">5</div>
    <div id="block3" class="block">3
      <div id="block4" class="block abs">4</div>
    </div>
  </div>
</div>
<div id="list"></div>

So you can see that hover propagates up the DOM elements. NOT drill through XY coordinates to see what it hits!

CSS

.block {
  margin: 50px;
  border: 1px solid blue;
  width: 50%;
  min-height: 30px;
  position: relative;
  background-color: rgba(250, 250, 250,1);
}

#list {
  position: fixed;
  top:20px;
  right:20px;
  border:1px solid gray;
  padding:10px;
  width: 100px;
  height:80vh;
}

.block:hover {
  background-color: rgba(220, 200, 200, 1);
}
/*
#block2:hover {
  background-color: rgba(200, 210, 200, 1);
}
#block3:hover {
  background-color: rgba(200, 200, 210, 1);
}
#block4:hover {
  background-color: rgba(210, 210, 200, 1);
}
#block5:hover {
  background-color: rgba(210, 200, 230, 1);
}
*/

.block.hovering {
  border: 2px solid red;
}

#block3 {
  height: 80px;
}
#block4 {
  right: -70%;
}
#block5 {
  width: 300px;
  right: -100%;
}

.block.abs {
  position: absolute;
  margin: 0px;
  height: 40px;
  width: 100px;
  
  top: 15px;
}

JavaScript

$(document).ready(
  function() {

    var currentTarget;
    document.onmouseleave = function(e) {
      e = e || window.event;
      if (currentTarget && currentTarget != e.target) {
        currentTarget.classList.remove('hovering');
        currentTarget = null;
      }
      console.log('doc leave');
    };

    document.getElementById('block1').onmousemove = mousemove;
    document.getElementById('block2').onmousemove = mousemove;
    document.getElementById('block3').onmousemove = mousemove;

    function mousemove(e) {
      e = e || window.event;
      e.stopPropagation();
      if (currentTarget && currentTarget != e.target) {
        currentTarget.classList.remove('hovering');
        currentTarget = e.target;
        e.target.classList.add('hovering');
      }
      console.log('block move', e.target.id);

    };

    function elementAtMousePosition() {
      return document.elementFromPoint(x, y);
    }
  }
);