maxqua72
maxqua72

Reputation: 391

jQuery ui drag and drop works incorrectly in Chrome when helper is set to clone

my application works fine in FF and IE but it works in an unexpected way in Chrome. I'm using jquery to implement a drag and drop behaviour of chess pieces on a chess board. I found out that using helper: "clone" option triggers the wrong behaviour in Chrome. The correct behaviour is: the piece must drop on the square it overlaps at least 50% (the default intersect tolerance). The Chrome behaviour is: the piece drops on the upper square it touches.

$(".piece-draggable").draggable({
    revert: true,
    // with "helper" option set to "clone" the drop is incorrect: moving only the 
    // top of the king piece to g5 
    // it happens the king is misplaced to g6 (onDrop is called from g6).
    // This behaviour affects only Chrome while FF works as expected.
    // without using the helper, all browsers works fine    
    helper: "clone",
    containment: ".board",
    start: onDragStart,
    stop: onDragStop
});

$(".square20").droppable({
    drop: onDrop
});

function onDragStart(event, ui) {
    $("#text").append("<p>start</p>");
    $(this).css("opacity", "0.35");
    $(ui.helper).css("opacity", "1");
}

function onDragStop(event, ui) {
    $(this).css("opacity", "1");
    $("#text").append("<p>stop</p>");
}

function onDrop(event, ui) {
    //ui.draggable.draggable('disable');
    //$(this).droppable('disable');
    ui.draggable.position({
        of: $(this),
        my: 'center',
        at: 'center'
    });


    ui.draggable.draggable('option', 'revert', false);
    $("#text").append("<p>" + "drop " + $(this).attr("id") + "</p>");
}


$(".piece-draggable").draggable('enable');

$(".square20").droppable('enable');​

Here is the jsfiddle example. You can try moving the black king to g5, just touching the g6 square: the king will be placed on g6!

How can I fix this nasty problem?

Upvotes: 2

Views: 1583

Answers (1)

J. Bruni
J. Bruni

Reputation: 20492

I was able to fix the behaviour by adding the following CSS snippet:

img.piece-draggable {
    width: 20px;
    height: 20px;
}

By observing the incorrect behaviour, it seemed to me that the cloned image was acting as if it had zero width and zero height, i.e., the upper-left corner of the absolute positioned image was dictating the DROP destination, ignoring the image dimensions.

So, my first try was to "provide" this "missing" width/height... and it worked.

Now, with the help of this useful "discovery" you can elaborate a more suitable solution, based on your needs and requirements...

Upvotes: 1

Related Questions