user3065931
user3065931

Reputation: 531

jQuery UI Drag and Drop Objects - difference between ui, ui.helper and this

Working on a drag and drop application and I'm getting a bit confused about which objects to base events on. For example when I initialise the draggable I set up a function to run on the drag call back and pass it ui so I can track its position:

jQuery( '.drag' ).draggable({
        helper : 'clone',
        drag : function ( event, ui ) { test(ui.helper, ui, this);}
});

function test(helper, drag_ui, drag_this){

    //check the type of each, and as expected each are objects
    console.log('HLEPER TYPE: '+jQuery.type(cln_h));//object
    console.log('UI TYPE: '+jQuery.type(cl));//object
    console.log('THIS TYPE: '+jQuery.type(this_elem));//object

    //lets try and get the top position of each
    console.log('helper.position.top:  '+helper.position.top);//undefined
    console.log('drag_ui.position.top:  '+drag_ui.position.top);//working
    console.log('jQuery(drag_this).position.top:  '+jQuery(drag_this).position.top);//undefined


    //So, the ui parameter gives us a result, ui.helper nothing, and this nothing. 
    //However, if I get the position() of the helper and this first, then I get results.


    //get pos first
    helper_pos = helper.position();
    console.log('helper_pos.top:  '+helper_pos.top);//working

    drag_this_pos = jQuery(drag_this).position();
    console.log('drag_this_pos.top:  '+drag_this_pos.top);//working, but different result   

    //So now i have some results, but the weird thing is that drag_this is different to ui, and ui.helper. 
}

What I want is to know the top position if the helper clone as I am dragging it. Different examples I've seen use any of these three: ui, ui.helper and this. What I would like to know is:

  1. What is the difference between them all? They are all objects but different properties?
  2. What is best practice in this scenario?

Look forward to learning a bit from this.

Thanks.

Upvotes: 1

Views: 877

Answers (1)

G.Mendes
G.Mendes

Reputation: 1201

The difference is subtle but exists, depending on the scenario. To state the differences we need to consider if you are using a helper or not.

Using a Helper: http://jsfiddle.net/6UL5A/2/

When we use a clone helper the draggable keeps on its position while you drag its clone.

-Retrieving ui or ui.helper position will get helper position, same results for both.

-Retrieving this position will get the selector position, and not its clone.

Without Helper: http://jsfiddle.net/6UL5A/3/

Here we have a different scenario, our draggable selector will move around, and not just its clone.

-Retrieving ui will get the selector position in relation to start position.

-Retrieving ui.helper or this will get the selector position in relation to whole viewport.


With that said, the best practice is the one that suits your design needs.

Upvotes: 1

Related Questions