For a class, I'm trying to make a drag and drop interface using only JQuery, no plugins. so far, it looks basically like this:

$(document).ready(function(){

$(".draggable").mousedown(Dragging); function Dragging(e) {

$(this).addClass("dragging")

     $(".dragging").live("mousemove", function()
    {
        var offset = $("#right").offset();
        var x = offset.left;
        $(".dragging").css("position", "relative");
        $(".dragging").css("left", e.pageX - x + -40);
    })
};

});

The problem is that mousemove only seems to fire once; that is, it jumps to the mouse position like I want it to, but then I move the mouse and it stays. Why would this be?

  • I'm sorry that I messed up the code area, by the way, but that is how it looks KJ Longuski almost 7 years ago
  • why do you have mousemove and addClass on different lines? they can be chained John Farrow almost 7 years ago
  • They are now, the question still stands KJ Longuski almost 7 years ago

1 answer

0
points

The mousemove event is not the root of the issue. You should have two separate behaviors: one for the mousedown (and mouseup) and another for the live mousemove.

Additionally, you should calculate and store the beginning position of the element as it relates to the mouse before it is dragged and dropped.

Here is some code to get started:

$('.draggable').bind('mousedown mouseup', function(e){
    var diffX = e.pageX - $(this).offset().left;
    var diffY = e.pageY - $(this).offset().top;
    /*TODO: establish if the element is relative to another parentOffset */
    $(this).toggleClass('dragging').data('offset', {x: diffX, y: diffY});
});
$('.dragging').live('mousemove', function(e){
    var offset = $(this).data('offset');
    /*TODO: include checks to make sure user has not dragged mouse out of window area*/
    $(this).css({left: e.pageX - offset.x, top: e.pageY - offset.y});
});

and here are the example styles i used:

.draggable{
    position:absolute;
    padding:10px;
    background:#dadada;
    top:0;
    left:0;
}
.draggable:hover{
    cursor:move;
}
.dragging{
    outline:1px dashed #999;
}

Good luck!

Answered almost 7 years ago by Paul Gueller