eapo eapo - 1 month ago 7
jQuery Question

Affecting only the hovered children without the parents

The following code adding a red shadow on every DOM element on hover, how can i mark only that element what is under the cursor?

$( "html *" ).hover(function() {
$( this ).css('box-shadow','inset 0 0 3px red');
}, function() {
$( this ).css('box-shadow','none');
}
);
});


Here is my jsfiddle: https://jsfiddle.net/eapo/7Lyt9qeb/2/

Answer

You want to take a look at document.elementFromPoint


Using the mousemove event, the target is what you are after

document.body.addEventListener("mousemove",function(e){
  // clear "hovered" class
  var elems = document.getElementsByClassName("hovered");
  for(var a=elems.length-1; a>=0; a--){elems[a].classList.remove("hovered");}

  //add "hovered" class to target
  e.target.classList.add("hovered");
});
div{
  display:inline-block;
  outline: 1px solid;
  font-size:0px;
  width:50%;
  height:50%;
}
div.hovered{
  background-color:rgba(255,0,0,0.5);
}
body{
  width:400px;
  height:400px;
}
<body>
<div>
  <div>
    <div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </div>
  <div>
    <div></div>
  </div>
</div>
</body>

Comments