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:


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


     $(".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 about 6 years ago
  • why do you have mousemove and addClass on different lines? they can be chained John Farrow about 6 years ago
  • They are now, the question still stands KJ Longuski about 6 years ago

1 answer


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:

    outline:1px dashed #999;

Good luck!

Answered about 6 years ago by Paul Gueller