CaribouCode
CaribouCode

Reputation: 14398

On mouseup get target of div below element

Say I have some markup like this:

<div class="something1">
  Content 1
</div>
<div class="something2">
  Content 2
</div>

<div class="drag">
  Draggable div
</div>

Now, I've written some jQuery to allow the .drag div to be dragged. At the end of the drag I do something like this:

$(document).on('mouseup',function(e){
  console.log(e.target); 
});

When I drag the div over .something1, the answer to e.target I would like is .something1. Instead, because .drag is being dragged under the mouse, when the mouseup function executes, the target is still the .drag div.

How do I see what div the mouse is over during the mouseup, ignoring the div being dragged? Equally, how do I use this method to see what div is being hovered over whilst the dragging is happening?

(If it helps to know, I'm trying to build drag and drop functionality)

Upvotes: 3

Views: 3071

Answers (1)

rogelio
rogelio

Reputation: 1571

You cannot fire a mouseup event because .drag isn't a child node of something1 or something2, then, always you will get e.target = .drag

But you have another options If you write your own code: I added an id attribute to each div for search reasons. (see js below)

<div class="something1" id="something">
    Content 1
</div>
<div class="something2" id="something">
    Content 2
</div>

<div class="drag">
    Drag me
</div>

To know which div you are, is necessary to know the mouse position and the div's area. See the next

function getHoverElement(x,y){
    element = "none";
    $('div#something').each(function(i){
        el = this;
        el_left = $(el).offset().left;
        el_right= $(el).offset().left + $(el).width();
        el_top = $(el).offset().top;
        el_bottom = $(el).offset().top + $(el).height();

        if (x >= el_left && x <= el_right) {
            if (y >= el_top && y <= el_bottom) {
                element = $(el).attr('class');
                return false;
            }
        }
    });
    return element;
}

x and y are passed from mouseup event. See the working example

Obviously, this solution is based on mouse position only and isn't considered the margins of draggable element. So, if you need to refine the code you need to look at the drag element borders.

Another solution is to use draggable/droppable methods from jquery-ui that cover this issue.

$(".something1, .something2").droppable({
    drop: function(event, ui) {
        console.log($(this).attr('id'));
    }
});

See the working example

Upvotes: 3

Related Questions