user1853128
user1853128

Reputation: 1114

Jquery Drag and Drop without plugins

I have tried to create a drag and drop plugin using JQuery.

$('.draggable').on{
  mousemove : function(){
    var mouseposition = { // this also needs to account for onclick offset of pointer vis-a-vis element
        x : pageX,
        y : pageY 
    };
    $(this).css({
      top : mouseposition.y,
      left : mouseposition.y
    });
  if( // this statement is kinda bogus, idea is to perform a collision detection via coordinate comparison
    $('.draggable').offset().top < $(.droppable').offset().top 
    &&
    $('.draggable').offset().left < $(.droppable').offset().left
  ) {
      alert('the item has been dropped');
  }
  }
});

Here is the demo link what I have tried.

Upvotes: 2

Views: 1377

Answers (2)

Chris
Chris

Reputation: 58182

I have reworked your code, and updated the fiddle. http://jsfiddle.net/XTMK8/2/

var dragging = undefined;

$('.draggable').on('mousedown', function(){
    dragging = $(this);
});

$('body').on('mousemove', function(e){
    if(typeof dragging != "undefined") {
        dragging.css({
             top : e.pageY - 50,
             left : e.pageX - 50
        });       
    }
});

$('body').on('mouseup', function(){
    dragging = undefined;
});

Collision Detection

I would then recommend using the following snippet to handle collision:

jQuery/JavaScript collision detection

Upvotes: 3

the_marcelo_r
the_marcelo_r

Reputation: 1856

I'm assuming this must be an academic task or you want to do it for learning purposes (otherwise, why someone wouldn't want to use JQuery UI's draggable?) but anyway, the link below should guide in the right direction: http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/

If you still want to know what's wrong with your code, I recommend starting over and add bit by bit to try to achieve the basic functionalities before coming up with a draggable and droppable at once, e.g., your mousemove function seems different from the one in JQuery's doc, I believe that, in order to retrieve pageX and pageY, you need the event object within the function's parameters:

$("#target").mousemove(function(event) {
  var msg = "Handler for .mousemove() called at ";
  msg += event.pageX + ", " + event.pageY;
  $("#log").append("<div>" + msg + "</div>");
});

Try to set some breakpoints using Firebug and see if all variables are being populated accordingly.

I hope that helps, cheers!

Upvotes: 0

Related Questions