MarkD
MarkD

Reputation: 4944

Determining all elements under a click with jquery

Lets say I have 3 divs, within a holder div:

<div class='holder'>
  <div id='back'></div>
  <div id='middle'></div>
  <div id='front'></div>
</div>

Those three divs (#back, #middle and #front) are all absolutely positioned, have z-index settings to stack them appropriately, and have varying degrees of overlap. e.g. css:

div.holder {
  position: relative;
  width: 400px;
  height: 400px;
}

div.holder > div {
  position: absolute;
  width: 150px;
  height: 150px;
  opacity: 0.25;
}

#back {
  top: 0px
  left: 0px;
  z-index: 1;
  background-color: #990000;
}

#middle {
  top: 100px;
  left: 100px;
  z-index: 2;
  background-color: #009900;
}

#front {
  top: 50px;
  left: 50px;
  z-index: 3;
  background-color: #000099;
}

I want to make #front clickable (e.g. using: $('#front').click()), but when clicked, I want to get a list of elements directly below that click. In the example above, there is a 50px x 50px area in the center of #front, where this would yield #back, #middle, and .holder. I know I can have the click event pass through to .holder, so that one is easy. But how do I identify if #back and #middle were under the click?

I have created a jsfiddle here: https://jsfiddle.net/hr2m2gck/

Upvotes: 2

Views: 184

Answers (2)

splitwire
splitwire

Reputation: 297

Try this:

$('#front').click(function(evt) {
    var siblingsAfter = $(evt.target).nextAll();
  });

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you could use elementsFromPoint(). This method accepts an X and Y coordinate and returns a collection of the elements in the DOM which occupy space at that point. You can simply get the coordinates of the mouse click from the event handler, something like this:

$(document).ready(function() {
  $(document).click(function(e) {
    var elements = document.elementsFromPoint(e.clientX, e.clientY);
    console.log(elements);
  })
});
div.holder {
  position: relative;
  width: 400px;
  height: 400px;
}

div.holder>div {
  position: absolute;
  width: 150px;
  height: 150px;
  opacity: 0.25;
}

#back {
  top: 0px left: 0px;
  z-index: 1;
  background-color: #990000;
}

#middle {
  top: 100px;
  left: 100px;
  z-index: 2;
  background-color: #009900;
}

#front {
  top: 50px;
  left: 50px;
  z-index: 3;
  background-color: #000099;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div id="back"></div>
  <div id="middle"></div>
  <div id="front"></div>
</div>

The caveat here is that this method is only supported in >IE10. It has full support in modern browsers, though.

Upvotes: 3

Related Questions