简体   繁体   中英

How to make a jquery-ui widget draggable

I need clear up some jquery-ui concepts and could use your help.

If I do the following:

$("<div></div>").draggable();

jquery-ui will create a draggable object that wraps the selected div. I have, however, created my own widget (using $.widget("namespace.mywidget" ), so, my first question would be, what happens when invoking this?

$("<div></div>").draggable().mywidget();

I suppose a mess ensues. In any case, I would like to define properties for the drag method, so I'd like to put that inside my widget. The second question is therefore: how do I extend $.ui.draggable ? Do you have any good tutorial? Simply calling this does not seem to be enough:

$.widget( "namespace.mywidget", $.ui.draggable, {} );

Thanks a bunch for any insights!

Just include it inside of your plugin. Make sure you include jqueryUI before your plugin code.

(function($){
    $.fn.myWidget = function(){
        return this.each(function(){
            $(this).draggable();
        });

    };
})(jQuery)

$('<div></div>').myWidget();  // this should be draggable.

http://jsfiddle.net/gJ3CN/2/

Before using draggable, make sure the element is in the DOM:

$('<div></div>').appendTo(document.body)

You can then chain together your widget and draggable:

   $('<div></div>').appendTo(document.body)
     .mywidget()
     .draggable();

You can set any parameters you'd like on each widget call. I created an example at jsfiddle.net/bseth99/LEY9A/ that builds a simple custom UI widget as a reference and for demonstration purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM