Nikhil Agarwal
Nikhil Agarwal

Reputation: 21

Highlighting innermost HTML element

I want to highlight the innermost HTML element on which my mouse pointer is. Since my page have scroll bars, using x,y coordinates will not help as an element will have different x,y positions on my screen depending on how much I scroll.

How do I achieve this using jQuery?

Upvotes: 2

Views: 53

Answers (1)

Dave
Dave

Reputation: 10924

You can use the mousemove event with event delegation to determine what element is the mouse is currently over.

Here's a simple example:

$("html").on("mousemove", "*", function(e) {
  $(".highlight").removeClass("highlight");
  $(e.target).addClass("highlight");
});
div {
  border: solid 1px black;
  padding: 0;
  margin: 0;
}

.a {
  height : 100px;
  width: 200px;
}

.b {
  height : 40px;
  width: 40px;
}

.c {
  height : 25px;
  width: 25px;
}

.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a">
  <div class="b"></div>
  <div class="b">
    <div class="c"></div>
  </div>
</div>

Upvotes: 1

Related Questions