1

I am trying to add some existing functionality to a site that uses jQuery (I want to get the draggable feature working with live()).

I found a bit of code which does it but I am having trouble getting it to work.

(function ($) {
   $.fn.liveDraggable = function (opts) {
      this.live("mouseover", function() {
         if (!$(this).data("init")) {
            $(this).data("init", true).draggable(opts);
         }
      });
   };
}(jQuery));

I added the code after I have loaded jQuery and jQuery UI and before I actually do anything with it, however, when I try to use it, I get the following error:

$('.myclass').liveDraggable({}) is undefined.

Can anyone help?

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
Dan
  • 1,065
  • 2
  • 9
  • 16
  • `$('.myclass').liveDraggable({})` is `undefined` because you don't return anything. – gen_Eric Jul 26 '11 at 13:15
  • 1
    Are your sure it's `liveDraggable` which it says is undefined? I assume you're including jQuery UI after jQuery core? – JAAulde Jul 26 '11 at 13:16
  • Yes, I've edited the question to clarify – Dan Jul 26 '11 at 13:16
  • 1
    @Rocket - true, the function should be defined and callable, but it is not adhering to proper plugin practices by returning the collection n order for chaining. @Dan - are you trying to chain something off of the call to `liveDraggable`? – JAAulde Jul 26 '11 at 13:17
  • Yes, a call to droppable – Dan Jul 26 '11 at 13:20
  • @Rocket, adding a return fixed the problem. Thanks all. – Dan Jul 26 '11 at 13:25

2 Answers2

4

You will need to include the jQuery UI script(s) for this to work (not just core jQuery), also see here.

Also it looks like that piece of code originated from this SO thread which has some usage examples as well: jQuery Drag And Drop Using Live Events

Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
4

Your code works fine. $('.myclass').liveDraggable({}) is going to return undefined because there is no return statement. Usually, you want to return this so you can chain calls.

(function ($) { 
   $.fn.liveDraggable = function (opts) {
      return this.live("mouseover", function() {
         if (!$(this).data("init")) {
            $(this).data("init", true).draggable(opts);
         }
      });
   };
}(jQuery));

Now you can chain this with other jQuery methods.

$('.myclass').liveDraggable({}).live('click', function(){
  // code
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337