views:

24

answers:

1

For a class, I have to make a Drag and Drop interface using only CSS, HTML 4.01, and Javascript with the JQuery library; no plugins allowed. I figure the best way to do this was aler the CSS position of the div I'm supposed to drag on mousedown and then on mouseup

 $(document).ready(function(){
    $(".draggable").mousedown(Dragging(this));
    function Dragging(draggableObject)
    {
        draggableObject.live("mousemove", function(){draggableObject.css(/*alters the position of the div*/)});
    };
});

My trouble is that draggableObject doesn't seem to have any CSS properties, I tried calling up an alert with its properties and apparently they're null. What am I doing wrong with passing the object, or anywhere else?

+1  A: 

Why doesn't it work? - By using Dragging(this) you're calling the function immediately, not running it when bound. Also the first parameter the function gets when run as an event handler is the event object.


It should look like this:

$(document).ready(function(){
   $(".draggable").mousedown(Dragging);
   function Dragging() {
     $(this).bind("mousemove", function(){
       $(this).css(/*alters the position of the div*/)
     });
   }
});

In an event handler this already refers to the element, there's no need to pass it around. You can also shorten it down like this:

$((function(){
   $(".draggable").mousedown(function () {
     $(this).mousemove(function(){
       $(this).css(/*alters the position of the div*/)
     });
   });
});

Note we're not using .live() here, it's not for this case (and can't be used without a selector), you just want .bind() directly (the .mousemove() shortcut above uses .bind() as well).

Nick Craver