Tien Do
Tien Do

Reputation: 11089

How to get element under mouse cursor while dragging another element?

I googled and found several answers but they was all about click or mousemove events which are not suitable for my question.

Basically I allow users to drag an item from a list and drop it on a folder in another list and I want to highlight element (in the folder list) whenever an item is dragging over it. Listening to mouseenter and mouseleave events on the folder list won't work. I tried with document.elementFromPoint in the dragging event (jQuery UI's Draggable drag) but unfortunately it returns the helper element instead of the element in the folder list. I think it's correct behavior since document.elementFromPoint returns the top most element under mouse cursor. But it doesn't solve my problem :(.

    $("#filelist li").draggable({
        helper: "clone",
        drag: function (event, ui) {
            console.log(event.pageX, event.pageY);

            var element = document.elementFromPoint(event.pageX, event.pageY);

            // element is helper element, instead of actual element under cursor which I want.
        }
    });
    $("#folderlist").droppable({
        drop: function (event, ui) {
        }
    });
    // These mouse events won't be triggered while dragging an item.
    $("#folderlist").on({
        "mouseenter": function (event) {
            this.style.backgroundColor = "#1c70cf";
        },
        "mouseleave": function (event) {
            this.style.backgroundColor = "";
        }
    }, "li");

Upvotes: 3

Views: 2652

Answers (1)

Flipke
Flipke

Reputation: 971

Apparently, the droppable has an hover function. http://jqueryui.com/droppable/#visual-feedback

$("#folderlist").droppable({
    hoverClass: "ui-state-hover",
    drop: function (event, ui) {
    }
});

Then add this to your css :

.ui-state-hover
{
    background-color: #1c70cf;
}

Upvotes: 1

Related Questions