Dan
Dan

Reputation: 1085

Extending jQuery

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?

Upvotes: 1

Views: 2023

Answers (2)

gen_Eric
gen_Eric

Reputation: 227310

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
});

Upvotes: 4

BrokenGlass
BrokenGlass

Reputation: 161002

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

Upvotes: 4

Related Questions