0

I have done successfully moved a image with arrow keys but now i want getting id behind the moved image. And here i want all div id when image overlap.

html

<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
<img id="image" src="http://placekitten.com/69/69" style="position:absolute;left:0; top:0; z-index: 1;" height="15" width="15">

css

body{background:yellow;}
#box2, 
#box3, 
#box4, 
#box5 {
  width: 50px;
  height: 50px;
  background: greenyellow;
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 2 
}

#box3 {
  top: 150px;
  left: 150px; 
}

#box4 {
  top: 50px;
  left: 250px;
}

Please check demostration link

https://jsfiddle.net/36y0ztn9/1/

  • 1
    Your image is not moving . please provide the full working code . – Pushprajsinh Chudasama Sep 14 '19 at 12:48
  • You should probably use [`getBoundingClientRect()` Method](https://www.w3schools.com/jsref/met_element_getboundingclientrect.asp) to get the positions of the boxes first and then when the image is moved, calculate the position of the image to check if it is inside one of the boxes. – Jay Surya Sep 16 '19 at 05:15
  • @PushprajsinhChudasama Please check link https://jsfiddle.net/p0nkfdwr/3/ – Praveen Kumar Sep 16 '19 at 05:23
  • @jaysurya I have already used that method thats method does not work me – Praveen Kumar Sep 16 '19 at 05:25
  • @PraveenKumar Why didn't it work? You might need to use it this way - https://stackoverflow.com/a/52477551/7314900. add the window scroll position to the values obtained by `getBoundingClientRect()` method. – Jay Surya Sep 16 '19 at 05:31
  • @jaysurya I want different result Please check demo link https://jsfiddle.net/p0nkfdwr/3/. here i want that div id which overlaped by image. – Praveen Kumar Sep 16 '19 at 05:39

2 Answers2

0

for getting id you can usedocument.querySelector('#idname) or document.getElementById('idname') in your JavaScript file.

0

Following up to my comments above,

document.elementFromPoint only gets the top most element - mozilla docs, which here is the image itself, so use a work around like setting display:none or pointer-events:none to the image to make the box as the top most elem and get the box Id. Then reset the value back.

Check this working fiddle, where I made some modifications to yours : https://jsfiddle.net/y6xsnc8h/1

Also Check this answer for a reusable function : https://stackoverflow.com/a/22428553/7314900

Jay Surya
  • 540
  • 1
  • 8
  • 18