eGo Gaming
eGo Gaming

Reputation: 41

jQuery - Find out which element is directly behind another

I am creating a little box opening game where my users can open a box and an animated spinner scrolls along all of the prizes and lands on their winning prize (indicated by the black line in the middle in the pic below)

Image of the spinner

After the animation, a whole bunch of box elements that represent the prizes are added to the page. What I am trying to figure out is:

Using jQuery, how can I find which box the black line lands on?

Any help would be appreciated, thanks.

HTML STRUCTURE

<section class="boxes box-background">
    <div class="winning-line" id="line">&nbsp;</div>
        <div class="container boxes-container">
            <div class="row">
                <div class="col-12">
                    <div class="open-box">
                        <div id="unbox-area" id="unbox">
                            <div id="cardList">
                               <div class="card" id="prize1">...</div>
                               <div class="card" id="prize2">...</div>
                               <div class="card" id="prize3">...</div>
                               //so on
                            </div>
                         </div>
                     </div>
                 </div>
             </div>
         </div>
     </div>
 </section>

PROBLEM

Currently, using the code below, I can only get the "open-box" element, not the actual individual "card" class element that the black line landed on.

let blackLineEl = document.getElementById("line");  
let rect = blackLineEl.getBoundingClientRect();
let left = rect.x;
let originalDisplay = blackLineEl.style.display;
blackLineEl.style.display = "none"
let winner = document.elementFromPoint(left, 180.0);
blackLineEl.style.display = originalDisplay
console.log(winner.className);

I have tried adjusting the static top position to different values, but no luck.

Upvotes: 4

Views: 118

Answers (1)

lior bakalo
lior bakalo

Reputation: 450

Try the elementFromPoint(x, y) method.

Since document.elementFromPoint returns the topmost element, you'll need to temporarily set your draggable to display:none or pointer-events:none to find elements below it.

Something like:

let lineEl = document.getElementById("blackLine")
let x = parseFloat(getComputedStyle(lineEl).left)
let y = parseFloat(getComputedStyle(lineEl).top)
let h = parseFloat(getComputedStyle(lineEl).height)

let originalDisplay = getComputedStyle(lineEl).display
  //hide black line to get element behind it
lineEl.style.display = "none"

let winningBox = document.elementFromPoint(x, y+0.5*h);
lineEl.style.display = originalDisplay

// Do something with winningBox

Edit: You can use Mike Abdullah's gist that gets all the elements in a given point

Upvotes: 1

Related Questions