azzy81
azzy81

Reputation: 2289

Access Jquery-UI draggable events from custom function

Heres my custom function called "doIt" which as im sure you can see simply allows someone to call .doIt() on a class or id and in this case makes the background color red and then makes the element draggable. (this is my first attempt so please be nice).

(function($) {
   $.fn.doIt = function(customOptions) {
      var options = $.extend({}, $.fn.doIt.defaultOptions, customOptions);
      return this.each(function() {
         var $this = $(this); 
         $this.on('click', function(e){
            e.preventDefault();
            $this.css("background-color", options.color);
            $this.draggable();
         });
      });
   };
   $.fn.doIt.defaultOptions = {
    color: "#000"   
   };               
})(jQuery);

because my function makes the element draggable I would like to use some of events tied to draggable like 'stop' for example so when the dragging has stopped I would like the user to be able to access the same event/ui info in the callback of stop.

However how can I interact with the stop event of draggable from my function?

What Im expecting to see is somethign like:

$("div#test").doIt({
    color: "#ffeeaa",
    stop: function(e, ui){

      //interact with draggable event/ui here.  
      //So 'e' and 'ui' would return me what the 'stop' event from draggable would normall return.

    }
});

Is this possible to do or am I barking up the wrong tree?

Upvotes: 0

Views: 807

Answers (1)

RustyTheBoyRobot
RustyTheBoyRobot

Reputation: 5955

You just need to pass your options to jQuery. Obviously, you are defining options above and beyond what jQuery uses, so you'll probably want to filter out the ones that jQuery doesn't care about, but I'm pretty sure that you don't have to; jQuery will just ignore the properties that it doesn't use.

So, you are specifically trying to hook into the stop event. To do this, change this line:

$this.draggable();

to this:

$this.draggable({
    stop: customOptions.stop   // Get the callback defined in custom options
});

If you don't have any naming collisions between your custom options and the options that jQuery defines, you could probably just do this:

$this.draggable(customOptions);

jQuery will call your function (passing the event and ui parameters to it) once the user has stopped dragging your draggable element.

Upvotes: 1

Related Questions