3

I am trying to create draggable chess pieces but I can't find any way to drop a piece on a square because when I hover over a droppable position while dragging a piece then the mouseenter event is not firing. I have noticed that z-index is the reason because when I put a lower z-index on a draggable piece then the mouseenter event works but this is not ideal since I can't see a piece that I am dragging anymore.

showing how mouseenter event doesn't fire while dragging

Here is a codepen that simulates the same behaviour (you have to open a console). When mouse enters a black box then mouseenter event fires but if mouse enters while dragging a blue box then mouseenter event doesnt fire.

Is there a way to force the mouseenter or mouseover event to fire even when the mouse is hidden behind another HTML element? My goal is to detect when I am dragging over a droppable position so I can move my piece from one div to the other. I have found similar issue in this old question but I really don't like either tracking x-y coords of every droppable div or creating transparent element over a droppable div with high z-index so I am hoping there is a cleaner solution for this.

hdw3
  • 871
  • 10
  • 28
  • Could you make a working snippet so it's easier to see what is going on. Thanks. Also I don't understand this syntax: makeDroppable(element: HTMLElement) – A Haworth Feb 20 '21 at 14:57
  • @AHaworth it isn't plain javascript, I am using typescript and angular. This is just a function that takes HtmlElement as argument. I will try to create a snippet later today – hdw3 Feb 20 '21 at 15:10
  • Thanks, maybe tag the question with the systems you are using so we don't try to interpret it as plain JS. – A Haworth Feb 20 '21 at 15:51
  • @AHaworth I don't see how typescript or angular is relevant here – hdw3 Feb 20 '21 at 15:55
  • @AHaworth I have swaped code from the post for codepen snippet https://codepen.io/hdw3/pen/poNrKpo to avoid confusion. Hope this helps – hdw3 Feb 20 '21 at 16:11

1 Answers1

1

Based on Forwarding Mouse Events through layers/divs, looks like you simply have to modify your draggable CSS by adding...

pointer-events: none;

...so that it becomes...

.draggable{
  cursor: grab;
  position:absolute;
  z-index: 5;
  --size: calc(100% - 2*var(--padding));
  pointer-events: none;
}

What does this do? When the drag starts and applies the draggable class to the element being dragged, it turns off mouse events for the dragged element, thus allowing the mouse events to pass through the dragged element to any elements underneath.

(See https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events for complete list of options and browser support.)

Trentium
  • 3,419
  • 2
  • 12
  • 19