hdw3
hdw3

Reputation: 951

How to fire mouseenter event when cursor is hidden behind other HTML element?

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.

Upvotes: 3

Views: 1062

Answers (1)

Trentium
Trentium

Reputation: 3719

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.)

Upvotes: 1

Related Questions